This Question have 3 answers right now.

c# String Length Event

Tags: c#
Question!

Basically I want to launch an event when a string reaches a specific length.

I have a Static String

Static String  _Info;

So i have My Delegate that has an integer as a Parameter !

public Delegate void ReachLengthHandler(int Length);

and My event :

public event ReachLengthHandler ReachLengthEvent;

And a Method that Keep addingSome informations to that string :

    public void AddInfo()
    {
     new Thread(() =>
    {
     while(true)
     _Info += ""; //Basically add the inputs of the user here ! 
     if (_Info.Length > 500)
      {
       if (ReachLengthEvent != null)
          ReachLengthEvent(_Info.Length);
      }
    }).Start();

    }

Do you think its the right way to do this event or there are any cleaner ways ?

EDIT : I want this event because I want to save this string in a Database table row so I don't want to expand the possible size of a row !

By : Buffer_z


Answers

As some pointed out in the comments, you may be trying to solve an instance of the XY Problem -- but assuming you're not, you are not approaching things in an object-oriented way, starting with encapsulation.

This could be a start, FWIW:

public class MaxLengthEventArgs : EventArgs
{
    public MaxLengthEventArgs(string value)
    {
        LastAppended = value;
    }

    public string LastAppended { get; private set; }
}

public delegate void MaxLengthEventHandler(object sender, MaxLengthEventArgs args);

public class StringAccumulator
{
    protected StringBuilder Builder { get; private set; }

    public StringAccumulator(int maxLength)
    {
        if (maxLength < 0)
        {
            throw new ArgumentOutOfRangeException("maxLength", "must be positive");
        }
        Builder = new StringBuilder();
        MaxLength = maxLength;
    }

    public StringAccumulator Append(string value)
    {
        if (!string.IsNullOrEmpty(value))
        {
            var sofar = value.Length + Builder.Length;
            if (sofar <= MaxLength)
            {
                Builder.Append(value);
                if ((OnMaxLength != null) && (sofar == MaxLength))
                {
                    OnMaxLength(this, new MaxLengthEventArgs(value));
                }
            }
            else
            {
                throw new InvalidOperationException("overflow");
            }
        }
        return this;
    }

    public override string ToString()
    {
        return Builder.ToString();
    }

    public int MaxLength { get; private set; }

    public event MaxLengthEventHandler OnMaxLength;
}

class Program
{
    static void Test(object sender, MaxLengthEventArgs args)
    {
        var acc = (StringAccumulator)sender;
        Console.WriteLine(@"max length ({0}) reached with ""{1}"" : ""{2}""", acc.MaxLength, args.LastAppended, acc.ToString());
    }

    public static void Main(string[] args)
    {
        var acc = new StringAccumulator(10);
        try
        {
            acc.OnMaxLength += Test;
            acc.Append("abc");
            acc.Append("def");
            acc.Append("ghij");
            Console.WriteLine();
            acc.Append("ouch...");
            Console.WriteLine("(I won't show)");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        Console.ReadKey();
    }
}

Also, keep in mind that strings in .NET are immutable.

Accumulating them using string concatenation, as you did in

_Info += ""

... isn't going to scale well (performance-wise).

'HTH,

By : YSharp


Usually eventhandler is used with specific signature.

public delegate void ReachLengthHandler(object sender, EventArgs args);
class Program
{
    public event ReachLengthHandler handler;

    private const int Threshhold = 500;

    public string Info
    {
        set
        {
            if (value.Length > Threshhold)
            {
                this.OnReachLength(null);
            }
        }
    }

    public void OnReachLength(EventArgs args)
    {
        this.handler?.Invoke(this, args);
    }
}


You can use a WHERE clause for this. Convert your INSERT VALUES to an INSERT SELECT and add a WHERE clause.

For example,

INSERT INTO fields (field_name, control_type_id, needs_approval)
SELECT
'Array Photos', 3, 0
WHERE Condition;

If Condition is true, it will insert the row. If Condition is false, the SELECT will return zero rows and thus the INSERT will insert zero rows.



Video about c# String Length Event