class Person { public string Name { get; init; } public int Age { get; init; } public Person() { } public Person(string name, int age) { Name = name; // Assign values in constructor Age = age; } }
var p1 = new Person { Name = "Steve", Age = 20 }; // Assign values in object initialization var p2 = new Person("Jack", 30); // Following statement is a compilation error as we can't change value of Age property p1.Age = 25;
// Immutable properties Hours, Minutes, Seconds are created from positional parameters public record Time(int Hours, int Minutes, int Seconds) { public int MilliSeconds { get; init; } // Init-only property } // Record with mutable properties public record Customer { public string Name { get; set; } public string Email { get; set; } };
var t1 = new Time(10, 20, 30) { MilliSeconds = 100 }; Console.WriteLine(t1); // calls built-in ToString() var t2 = new Time(10, 20, 30); Console.WriteLine(t1.Hours); // Access immutable property Time t3 = t1 with { Hours = 20 }; // Make a copy of t1 and change only Hours to 20 Console.WriteLine(t3); var c1 = new Customer { Name = "A", Email = "a@gmail.com" }; var c2 = new Customer { Name = "A", Email = "a@gmail.com" }; Console.WriteLine(c1 == c2); // Uses built-in value equality c2.Email = "a@yahoo.com"; // Can modify through setter method Console.WriteLine(c1 == c2);
Time { Hours = 10, Minutes = 20, Seconds = 30, MillSeconds = 100 } 10 Time { Hours = 20, Minutes = 20, Seconds = 30, MillSeconds = 100 } True False
using System; using CsharpDemo; // Namespace for Person class Console.WriteLine("Hello!"); Console.WriteLine($"No. of command line arguments : {args.Length}"); // args is available // Use other classes of the project - CsharpDemo.Person var v1 = new Person { Name = "Anders", Age = 55 }; Console.WriteLine(v1.Name);
int a = 150; char ch = ':'; Console.WriteLine(a is >= 10 and <= 20 or >=100 and <= 200); // True Console.WriteLine(ch is '.' or ',' or ':' or ';'); // True Console.WriteLine(ch is (>='A' and <='E') or (>= 'a' and <= 'e')); // False string msg = ch switch { '.' => "Dot", ':' => "Colon", ';' => "Semicolon", '+' or '-' => "Operator", _ => "Unknown" }; Console.WriteLine(msg); // Colon
void Print(Person p) { // code } // Create an object of type Person Person p1 = new() { Name = "Abc", Age = 20 }; // Using object initializer // Passing parameter of type Person Print(new("Abc", 20));