Pattern matching example

				
					
dashedLine("50");
newDashed("100");
Console.WriteLine(isIdesOfMarch(new DateTime(DateTime.Today.Year, 1, 13)));
Console.WriteLine(isIdesOfMarch(new DateTime(DateTime.Today.Year, 3, 15)));
Console.WriteLine(isIdesOfMarch(new DateTime(DateTime.Today.Year, 3, 17)));


//is expression...to test the constant pattern
//is expression also used to with whats called declaration pattern
string? str = null;

if (str is not null)
    Console.WriteLine("not null");
else
    Console.WriteLine("null");

//declaration pattern
void newDashed(object o)
{
    //"50"..l=50
    //50...l=50
    if (o is int l || (o is string s && int.TryParse(s, out l)))
    {
        string str = new string('-', l);
        Console.WriteLine(str);
    }
}

void dashedLine(object o)
{
    int l = 0;
    if (o.GetType() == typeof(int))
    {
        l = (int)o;

    }
    string s;
    if (o.GetType() == typeof(string))
    {
        s = (string)o;
        if (!int.TryParse(s, out l))
        {
            l = 0;
        }
    }
    if (l > 0)
    {
        string str = new string('-', l);
        Console.WriteLine(str);
    }
}



//property pattern
//Ides of march is - march 15th in Julius Ceasar..
bool isIdesOfMarch(DateTime date)
{
    return (date is { Month: 3, Day: 15 or 17 });
    //return (date is { Month: 3, Day: 15 });
}

				
			

Leave a Comment