This document provides an overview of key C# concepts like classes, functions, properties, access modifiers, and static components. It includes examples of using constructors to initialize objects, defining methods with parameters and return types, creating read-only and read-write properties, and demonstrating the differences between public, private, protected, and internal access levels. Static features are explained, such as defining static properties, methods, and constructors that get called before object instantiation.
4. Constructor
• Constructors are used to create and initialize any object member
variables when you use the 'new' expression to create an object of
a class.
5. Functions/Methods
• A function allows you to encapsulate a piece of code and call it from
other parts of your code.
<visibility> <return type> <Name>(<parameters>)
{
<function code>
return <returned object>;
}
6. Preperties
• A property is a member that provides a flexible mechanism to read,
write, or compute the value of a private field.
class User
{
private string _country;//backed field
public string FirstName { get; set; }//backed field will be created automatically
public string LastName { get; set; }
public string FullName => FirstName + " " + LastName; //Read only property
public bool IsInitialized // ReadOnly property
{
get { return !string.IsNullOrEmpty(FirstName) && !string.IsNullOrEmpty(LastName); }
}
public string Country//property using backed field
{
get { return string.Format("I live in {0}", _country); }
set { _country = value; }
}
}
7. Access modifiers
• public: access is not restricted
• private: access is limited to the containing type
• protected: access is limited to the containing class or types derived
from the containing class
• internal: access is limited to the current assembly
• protected internal: access is limited to the current assembly or types
derived from the containing class
8. static
• static function
• static property
• static class
class Animal
{
public static int AnimalCount { get; private set; }
private string Name;
public Animal()
{
Name = "No name defined.";
AnimalCount++;
}
public Animal(string name)
{
Name = name;
AnimalCount++;
}
public void PrintName()
{
Console.WriteLine(Name);
}
public static void GetInfo()
{
Console.WriteLine("My mission is to be an animal");
}
}
Animal.GetInfo(); //prints message
Animal a1 = new Animal();
Animal a2 = new Animal("Cow");
Animal a3 = new Animal();
a2.PrintName();//prints Cow
a3.PrintName();// pring 'no name defined' message
Console.WriteLine(Animal.AnimalCount); // outputs 3
9. Static constructor
• A static constructor is used to initialize any static data, or to perform a
particular action that needs to be performed once only. It is called
automatically before the first instance is created or any static
members are referenced.