C#

C#: 25-Class get/set

  • using getter/setters allows for logic to be used in the process
  • for gets, null checking can be performed for Singleton Design Patterns or different things can be returned based on state/value.
  • for sets, null checking & data validation can be performed on the incoming values

Object Instantiation with Property Sets

See Also: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

When an object is instantiated, the values can be set in the same statement

Car myCar = new Car{Type="Honda",Price=15000};

 

Tags

C#: 24-String Interpolation

//String Formatting Syntax
Console.WriteLine("System: {0}, Priority: {1}, Msg: {2}", system , priority, msg);
//String Interpolation
Console.WriteLine($"System: {system}, Priority: {priority}, Msg: {msg}");

 

Tags

C#: 22-Named and Optional Arguments

Optional Arguments

When arguments are given default values, they become optional

constants can be used


 

    class Logger
    {
        //using Named argument requires static constant variable...
        //..... const is static, so its redundant to use static
        //static string DefaultSystemName = "EmployeeTracker";
        const string DefaultSystemName = "EmployeeTracker";

        //priority type & system that throws log msg
        public static void Log(string msg, string system = DefaultSystemName, int priority=1)
        {
            Console.WriteLine("System: {0}, Priority: {1}, Msg: {2}", system , priority, system);
        }
    }


 

Named Arguments

Name arguments can be used in cases where a placeholder is needed for multi-argument methods with optional arguments

Tags

C#: 21-Extension Methods

Declaration

        // this extends the 'string' type
        // this is self-referencing
        // returns int
        public static int toInt(this string value)
        {
            return int.Parse(value);
        }

Usage

return Console.ReadLine().toInt();


 

Tags
Subscribe to C#