C# – Properties

Properties

Similar to fields but give more control to getting and setting value without exposing internal details to the user property. Get accessor runs when property is read, returns a value.
Set accessor is to assign to property, and has implicit parameter named value.

public class Stock
{
    decimal currentPrice; // The private "backing" field
    public decimal CurrentPrice // The public property
    {
        get { return currentPrice; }
        set { currentPrice = value; }
    }
}

Modifiers

  1. Static : static
  2. Access modifiers: public, internal, private, protected
  3. Inheritance modifiers: new, virtual, abstract, override, sealed
  4. Unmanaged: unsage, extern

Read-only and calculated properties

  • A property is read-only if it specifies only a get accessor.
  • A property typically has a dedicated backing field to store the underlying data.
  • Property can also be computed from other data.
decimal currentPrice, sharesOwned;

public decimal Worth
{
     get { return currentPrice * sharesOwned; }
}

Expression-bodied properties

Expression-bodied property can declare read-only property.

public decimal Worth => currentPrice * sharesOwned;

Automatic properties

An automatic property declaration instructs the compiler to provide this implementation. The compiler automatically generates private backing field that cannot be referred.

public class Stock
{
...
    public decimal CurrentPrice { get; set; }
}

Property initializers (C# 6)

You can add a property initializer to automatic properties.

public decimal CurrentPrice { get; set; } = 123;

Properties with an initializer can be read-only

public int Maximum { get; } = 999;

get and set accessibility

The get and set accessors can have different access levels.

public class Foo
{
   private decimal x;
   public decimal X
   {
      get { return x; }
      private set { x = Math.Round (value, 2); }
   }
}

CLR property implementation

property accessors internally compile to methods called get_XXX and set_XXX:

public decimal get_CurrentPrice {...}
public void set_CurrentPrice (decimal value) {...}

C# – this Reference

this Reference

The this keyword refers to the current instance of a class and it is also used as a modifier of the first parameter of an extension method.

public class Panda
{
   public Panda Mate;
   public void Marry (Panda partner)
  {
     Mate = partner;
     partner.Mate = this;
  }
}

The this reference is valid only within non static members of a class or struct.

this is used to qualify members hidden by similar names.

public Employee(string name, string alias)
{
  //this to qualify the fields, name and alias
  this.name = name;
  this.alias = alias;
}

this is used to pass an object as a parameter to other methods

CalTax(this);

this is to declare indexers.

public int this[int param]
{
    get { return array[param]; }
    set { array[param] = value; }
}

Example

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Employee E1 = new Employee("Just","Lee");
            E1.printEmployee();
        }
    }
    
    class Employee
    {
       //fields
       private string name;
       private string alias;
       private decimal salary = 3000.00m;
        
       //constructor
       public Employee(string name, string alias)
       {
           this.name = name;
           this.alias = alias;
       }
        
       //print method
       public void printEmployee()
       {
         Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
        // Passing the object to the CalcTax method by using this:
        Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
       }
        
        //property
        public decimal Salary
        {
            get { return salary;}
        }
    }
    
    class Tax
    {
       public static decimal CalcTax(Employee E)
       {
         return 0.08m * E.Salary;
       }
    }
}

C# – Object Initializers

Object Initializers

Any accessible fields or properties of an object can be set via an object initializer directly after construction.

public class Bunny
{
	public string Name;
	public bool LikesCarrots;
	public bool LikesHumans;

	public Bunny () {}
	public Bunny (string n) { Name = n; }
}

// Note parameterless constructors can omit empty parentheses
Bunny b1 = new Bunny { Name="Bo", LikesCarrots=true, LikesHumans=false };
Bunny b2 = new Bunny ("Bo") { LikesCarrots=true, LikesHumans=false };

Is equivalent to:

Bunny temp1 = new Bunny(); // temp1 is a compiler-generated name
temp1.Name = "Bo";
temp1.LikesCarrots = true;
temp1.LikesHumans = false;
Bunny b1 = temp1;


Bunny temp2 = new Bunny ("Bo");
temp2.LikesCarrots = true;
temp2.LikesHumans = false;
Bunny b2 = temp2;

Object Initializers Versus Optional Parameters

Instead of using object initializers, we could make Bunny’s constructor accept
optional parameters.

public Bunny (string name,
bool likesCarrots = false,
bool likesHumans = false)
{
Name = name;
LikesCarrots = likesCarrots;
LikesHumans = likesHumans;
}

This would allow us to construct a Bunny as follows:

Bunny b1 = new Bunny (name: "Bo",likesCarrots: true);

Advantage

  1. Can make fields or properties readonly./li>
  2. Making fields or properties read-only is good practice when there’s no reason to change throughout the life of the object.

Disadvantage
Each optional parameter value is baked into the calling site.
The compiler will translate into:

Bunny b1 = new Bunny ("Bo", true, false);

This can be problematic if we instantiate the Bunny class from another assembly and
later modify Bunny by adding another optional parameter—such as likesCats.

C# – Constructors

Constructors

Constructors initialize code on class or struct. Defined like methods except method name is same as class name with no return type defined. It initializes the data member of the new object.

//class
public class Panda
{
	//define field
	string name;

	//constructor with the parameter defined
	public Panda (string n)
	{
	   //initialization code and set up field
	   name = n;
	}
}
//Calling the constructor
Panda p = new Panda("Tommy");

//parameterless constructor
public class Taxi
{
    public bool isInitialized;
    public Taxi()
    {
        isInitialized = true;
    }
}

class TestTaxi
{
    static void Main()
    {
        Taxi t = new Taxi();
        Console.WriteLine(t.isInitialized);
    }
}

In this example, The Taxi class is instantiated with new operator then constructor is invoked after memory allocation.

The default constructor takes no parameter and gets invoked when the object is instantiated with new operator.

If the class is not static and no constructor is defined then the compiler assigns a default public constructor.

The class can be prevented by having a private constructor.

Structs cannot contain explicit constructors, compile provides one by default.

Constructors that take parameters must be called through a new statement or a base statement.

public class Employee
{
    public int salary;

    public Employee(int annualSalary)
    {
        salary = annualSalary;
    }

    public Employee(int weeklySalary, int numberOfWeeks)
    {
        salary = weeklySalary * numberOfWeeks;
    }
}

Employee e1 = new Employee(200);
Employee e2 = new Employee(6,9);

Classes and structs can also define multiple constructors, and neither is required to define a default constructor.

A constructor can use the base keyword to call the constructor of a base class.

namespace Rextester
{
    public class Program
    {
                
        public static void Main(string[] args)
        {
            Manager m = new Manager(200);
           
        } 
    }
    
    public class Manager : Employee
    {
        public Manager(int Salary) : base(Salary){}

    }
    
    public class Employee {
         
        public Employee(int Salary) { Console.WriteLine("Employee with param");}
    
    }
  
}

The base keyword can be used with or without parameters.

//With parameter
public Manager(int Salary) : base(Salary){}

//Without Parameter
public Manager(): base(){}

If a base-class constructor is not called explicitly by using the base keyword, the default constructor, if there is one, is called implicitly.

If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor by using base.

A constructor can invoke another constructor in the same object by using the this keyword.

namespace Rextester
{
    public class Program
    {
                
        public static void Main(string[] args)
        {
            Manager m = new Manager(200,5);
            Console.WriteLine(m.salary);
           
        } 
    }
    
    public class Manager
    {
        public int salary;
        public Manager(int Salary, int weeks) : this (Salary * weeks)
        {
           
        }
        
        public Manager(int annualsalary)
        {
           salary = annualsalary;
        }

    }
    
  
}

Instance Constructors

Instance constructors are used to create and initialize any instance member variables when you use the new expression to create an object of a class.

Instance constructors can also be used to call the instance constructors of base classes. The class constructor can invoke the constructor of the base class through the initializer.

Private Constructors

  • Used in classes that contain static members only.
  • Class with private constructors cannot create instances of the class.
  • Declaration of empty constructor prevents the generation of default constructor.
  • Default modifier for the constructor is private.
  • Private constructors are used to prevent creating instances of a class when there are no instance fields or methods.
  • If all the methods in the class are static, consider making the complete class static.
class NLog
{
    // Private Constructor:
    private NLog() { }

    public static double e = Math.E;  //2.71828...
}
using System;

namespace Rextester
{
    public class Program
    {
                
        public static void Main(string[] args)
        {
           Maths m = new Maths(10,5);
           //m.GetX();
           Console.WriteLine(m.GetX()); 
            
        } 
    }
    
    class Maths
    {
        //private default constructor - parameterless
        private Maths() {}
        
        //fields
        private int x ;
        private int y ;
        
        //public construtor with parameter
        public Maths(int x1, int y1)
        {
          x = x1;
          y = y1;  
        }
        
        //methods
        public int GetX()
        {
            return x;
        }
        
    }
  
}

Static Constructors

A static constructor is used to initialize any static data or perform action that needs to be performed only once and it is called automatically before the first instance.

class SimpleClass
{
	
    // Static variable that must be initialized at run time.
    static readonly long baseline;

    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}

A static constructor does not take access modifiers or have parameters.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

A static constructor cannot be called directly.

The user has no control on when the static constructor is executed in the program.

Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Related Article
Using Static

Copy Constructors

Copy constructor takes the argument as an instance of a type. Copy constructor is used to create a new object by duplicating the state of an existing object, and done by copying the value of existing object.

When we copy object, it doesn’t copy but it actually creates object reference, that is why copy constructor become handy.

class Person
{
    // Copy constructor.
    public Person(Person previousPerson)
    {
        Name = previousPerson.Name;
        Age = previousPerson.Age;
    }

    //// Alternate copy constructor calls the instance constructor.
    //public Person(Person previousPerson)
    //    : this(previousPerson.Name, previousPerson.Age)
    //{
    //}

    // Instance constructor.
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public int Age { get; set; }

    public string Name { get; set; }
    
    public string Details()
    {
        return Name + " is " + Age.ToString();
    }
}

class TestPerson
{
    static void Main()
    {
        // Create a Person object by using the instance constructor.
        Person person1 = new Person("George", 40);

        // Create another Person object, copying person1.
        Person person2 = new Person(person1);

        // Change each person's age. 
        person1.Age = 39;
        person2.Age = 41;

        // Change person2's name.
        person2.Name = "Charles";

        // Show details to verify that the name and age fields are distinct.
        Console.WriteLine(person1.Details());
        Console.WriteLine(person2.Details());
    }
}
// Output: 
// George is 39
// Charles is 41

Instance constructor modifiers

  1. Access modifier – public, internal, private, protected
  2. Unmanaged code modifiers – unsafe, extern

Overloading constructors

Class and structs allow overload constructors. To avoid duplication one constructor may call another using this keyword.

using System;
public class Wine
{
public decimal Price;
public int Year;
public Wine (decimal price) { Price = price; }
public Wine (decimal price, int year) : this (price) { Year = year; }
}

When one constructor calls another, the called constructor executes first.
You can pass an expression into another constructor as follows:

public Wine (decimal price, DateTime year) : this (price, year.Year) { }

Implicit parameterless constructors

For classes, the C# compiler automatically generates a parameterless public constructor if and only if you do not define any constructors.

Constructor and field initialization order

Field initializations occur before the constructor is executed and in the declaration order of the fields.

Nonpublic constructors

  • Constructors do not need to be public
  • Common reason to have a nonpublic constructor is to control instance creation via a static method call.
  • The static method could be used to return an object from a pool rather than necessarily creating a new object, or return various subclasses based on input arguments.

C#- Methods

Methods

  • Receives input from the parameters and output back using the return type.
  • Can have void return type where it doesn’t return any value
  • Method signature must be unique within the type

Modifiers

  1. Static : static
  2. Access modifiers: public, internal, private, protected
  3. Inheritance modifiers: new, virtual, abstract, override, sealed
  4. Partial: partial
  5. Unmanaged: unsage, extern
  6. Asynchronous: async

Expression-bodied methods (C# 6)

Expression-bodied method uses fat arrow to replace braces and return keyword and can also have void type.

int Foo (int x) { return x * 2; }
equals to
int Foo (int x) => x * 2;
void method
void Foo (int x) => Console.WriteLine (x);

Overloading methods

Methods with same name with different signatures and same return type

Pass-by-value versus Pass-by-reference

Whether a parameter is pass-by-value or pass-by-reference is also part of the signature.
Foo(int) can coexist Foo( ref int) or Foo(out int) but Foo(ref int) cannot coexist Foo(out int).