C Sharp Syntax Part-3

Classes

Classes are self-describing user-defined reference types. Essentially all types in the .NET Framework are classes, including structs and enums, that are compiler generated classes. Class members are private by default, but can be declared as public to be visible outside of

the class or protected to be visible by any descendants of the class.

the class or protected to be visible by any descendants of the class. 

String class
The System.String class, or simply string, represents an immutable sequence of unicode characters (char).
Actions performed on a string will always return a new string.
    string text = "Hello World!";
    string substr = text.Substring(0, 5);
    string[] parts = text.Split(new char[]{ ' ' });
The System.StringBuilder class can be used when a mutable "string" is wanted.
    StringBuilder sb = new StringBuilder();
    sb.Append('H');
    sb.Append("el");
    sb.AppendLine("lo!");
Interface
Interfaces are data structures that contain member definitions with no actual implementation. A variable of an interface type is a reference to an instance of a class which implements this interface.
Delegates
C# provides type-safe object-oriented function pointers in the form of delegates.
Events
Events are pointers that can point to multiple methods. More exactly they bind method pointers to one identifier. This can therefore be seen as an extension to delegates. They are typically used as triggers in UI development. The form used in C# and the rest of the Common Language Infrastructure is based on that in the classic Visual Basic.
Nullable types
Nullable types were introduced in C# 2.0 firstly to enable value types to be null (useful when working with a database).
Pointers
C# has and allows pointers to selected types (some primitives, enums, strings, pointers, and even arrays and structs if they contain only types that can be pointed) in unsafe context: methods and codeblock marked unsafe. These are syntactically the same as pointers in C and C++. However, runtime-checking is disabled inside unsafe blocks.

Dynamic
Type dynamic is a feature that enables dynamic runtime lookup to C# in a static manner. Dynamic denotes a variable with an object with a type that is resolved at runtime, as opposed to compile-time, as normally is done.
dynamic x = new AAA();
x.DoSomething();  // Will compile and resolved at runtime. An exception will be thrown if invalid.
When instantiating anonymous type declaration with the same signature the type is automatically inferred by the compiler.
var carl = new { Name = "Carl", Age = 35 }; // Name of the type is only known by the compiler.
var mary = new { Name = "Mary", Age = 22 }; // Same type as the expression above
Boxing and unboxing
Boxing is the operation of converting a value of a value type into a value of a corresponding reference type. Boxing in C# is implicit.
Unboxing is the operation of converting a value of a reference type (previously boxed) into a value of a value type. Unboxing in C# requires an explicit type cast.
Example:
int aaa = 42;         // Value type.
object bar = aaa;     // aaa is boxed to bar.
int aaa2 = (int)bar;  // Unboxed back to value type.
Object-oriented programming (OOP)
C# has direct support for object-oriented programming.
Objects
An object is created with the type as a template and is called an instance of that particular type.
In C#, objects are either references or values. No further syntactical distinction is made between those in code.
object class
All types, even value types in their boxed form, implicitly inherit from the System.Object class which is the ultimate base class of all objects. The class contains the most common methods shared by all objects. Some of these are virtual and can be overridden.
Classes inherit System.Object either directly or indirectly through another base class.
Classes
Classes are fundamentals of an object-oriented language such as C#. They serve as a template for objects. They contain members that store and manipulate data in a real-lifelike way.
Declaration
A class is declared like this:
class AAA
{
    // Member declarations
}
Partial class
partial class is a class declaration whose code is divided into separate files. The different parts of a partial class must be marked with keyword partial.
// File1.cs
partial class AAA
{
    ...
}

// File2.cs
partial class AAA
{
    ...
}
Initialization
Before you can use the members of the class you need to initialize the variable with a reference to an object. To create it you call the appropriate constructor using the new keyword. It has the same name as the class.
AAA aaa = new AAA();
For structs it is optional to explicitly call a constructor because the default one is called automatically. You just need to declare it and it gets initialized with standard values.
Object initializers
Provides a more convenient way of initializing public fields and properties of an object. Constructor calls are optional when there is a default constructor.
Person person = new Person {
    Name = "John Doe",
    Age = 39
};

// Equal to
Person person = new Person();
person.Name = "John Doe";
person.Age = 39;
Collection initializers
Collection initializers give an array-like syntax for initializing collections. The compiler will simply generate calls to the Add-method. This works for classes that implement the interface ICollection.
List<int> list = new List<int> {2, 5, 6, 6};

// Equal to
List<int> list = new List<int>();
list.Add(2);
list.Add(5);
list.Add(6);
list.Add(6);
Accessing members
Members of an instance and static members of a class are accessed using the . operator.
Accessing an instance member
Instance members can be accessed through the name of a variable.
string aaa = "Hello";
string aaaUpper = aaa.ToUpper();
Accessing a static class member
Static members are accessed by using the name of the class or other type.
int r = String.Compare(aaa, aaaUpper);
Modifiers
Modifiers are keywords used to modify declarations of types and type members. Most notably there is a sub-group containing the access modifiers.
Class modifiers
  • abstract - Specifies that a class only serves as a base class. It must be implemented in an inheriting class.
  • sealed - Specifies that a class cannot be inherited.
Class member modifiers
  • const - Specifies that a variable is a constant value that has to be initialized when it gets declared.
  • event - Declares an event.
  • extern - Specify that a method signature without a body uses a DLL-import.
  • override - Specify that a method or property declaration is an override of a virtual member or an implementation of a member of an abstract class.
  • readonly - Declare a field that can only be assigned values as part of the declaration or in a constructor in the same class.
  • unsafe - Specifies an unsafe context, which allows the use of pointers.
  • virtual - Specifies that a method or property declaration can be overridden by a derived class.
  • volatile - Specifies a field which may be modified by an external process and prevents an optimizing compiler from modifying the use of the field.
static modifier
The static modifier states that a member belongs to the class and not to a specific object. Classes marked static are only allowed to contain static members. Static members are sometimes referred to as class members since they apply to the class as a whole and not to its instances.
public class AAA
{
    public static void Something()
    {
        ...
    }
}
// Calling the class method.
AAA.Something();
Access modifiers
The access modifiers, or inheritance modifiers, set the accessibility of classes, methods, and other members. Something marked public can be reached from anywhere. private members can only be accessed from inside of the class they are declared in and will be hidden when inherited. Members with the protected modifier will be private, but accessible when inherited. internal classes and members will only be accessible from the inside of the declaring assembly.
Classes and structs are implicitly internal and members are implicitly private if they do not have an access modifier.
public class AAA
{
    public int Do()
    {
        return 0;
    }

    public class Bar
    {

    }
}
Constructors
A constructor is a special method that is called automatically when an object is created. Its purpose is to initialize the members of the object. Constructors have the same name as the class and do not return anything. They may take parameters like any other method.
class AAA
{
    AAA()
    {
        ...
    }
}
Constructors can be public, private, or internal.
Destructor
The destructor is called when the object is being collected by the garbage collector to perform some manual clean-up. There is a default destructor method called finalize that can be overridden by declaring your own.
The syntax is similar to the one of constructors. The difference is that the name is preceded by a ~ and it cannot contain any parameters. There cannot be more than one destructor..
class AAA
{
    ...

    ~AAA()
    {
        ...
    }
}
Finalizers are always private.
Methods
Like in C and C++ there are functions that group reusable code. The main difference is that functions, just like in Java, have to reside inside of a class. A function is therefore called a method. A method has a return value, a name and usually some parameters initialized when it is called with some arguments. It can either belong to an instance of a class or be a static member.
class AAA
{
    int Bar(int a, int b)
    {
        return a%b;
    }
}
A method is called using . notation on a specific variable, or as in the case of static methods, the name of a type.
AAA aaa = new AAA();
int r = aaa.Bar(7, 2);

Console.WriteLine(r);
ref and out parameters
One can explicitly make arguments be passed by reference when calling a method with parameters preceded by keywords ref or out. These managed pointers come in handy when passing variables that you want to be modified inside the method by reference. The main difference between the two is that an out parameter must have been assigned within the method by the time the method returns, while ref need not assign a value.
void PassRef(ref int x)
{
    if(x == 2) x = 10;
}
int Z;
PassRef(ref Z);

void PassOut(out int x)
{
    x = 2;
}
int Q;
PassOut(out Q);
Fields
Fields, or class variables, can be declared inside the class body to store data.
class AAA
{
    double aaa;
}
Fields can be initialized directly when declared (unless declared in struct).
class AAA
{
    double aaa = 2.3;
}
Modifiers for fields:
  • const - Makes the field a constant.
  • private - Makes the field private (default).
  • protected - Makes the field protected.
  • public - Makes the field public.
  • readonly - Allows the field to be initialized only once in a constructor.
  • static - Makes the field a static member.
Properties
Properties bring field-like syntax and combine them with the power of methods. A property can have two accessors: get and set.
class Person
{
    string name;

    string Name
    {
        get { return name; }
        set { name = value; }
    }
}

// Using a property
Person person = new Person();
person.Name = "Robert";
Modifiers for properties:
  • private - Makes the property private (default).
  • protected - Makes the property protected.
  • public - Makes the property public.
  • static - Makes the property a static member.
Modifiers for property accessors:
  • private - Makes the accessor private.
  • protected - Makes the accessor protected.
  • public - Makes the accessor public.
The default modifiers for the accessors are inherited from the property. Note that the accessor's modifiers can only be equal or more restrictive than the property's modifier.
Automatic properties
A feature of C# 3.0 is auto-implemented properties. You define accessors without bodies and the compiler will generate a backing field and the necessary code for the accessors.
public double Width
{
    get;
    private set;
}
Indexers
Indexers add array-like indexing capabilities to objects. They are implemented in a way similar to properties.
class IntList
{
   int[] items;

   int this[int index]
   {
        get { return this.items[index]; }
        set { this.items[index] = value; }
    }
}

// Using an indexer
IntList list = new IntList();
list[2] = 2;
Inheritance
Classes in C# may only inherit from one class. A class may derive from any class that is not marked as sealed.
class A
{

}

class B : A
{

}
virtual
Methods marked virtual provide an implementation, but they can be overridden by the inheritors by using the override keyword.
The implementation is chosen by the actual type of the object and not the type of the variable.
class Operation
{
    public virtual int Do()
    {
        return 0;
    }
}

class NewOperation : Operation
{
    public override int Do()
    {
        return 1;
    }
}
new
When overloading a non-virtual method with another signature, the keyword new may be used. The used method will be chosen by the type of the variable instead of the actual type of the object.
class Operation
{
    public int Do()
    {
        return 0;
    }
}

class NewOperation : Operation
{
    public new double Do()
    {
        return 4.0;
    }
}
This demonstrates the case:
NewOperation operation = new NewOperation();

// Will call "double Do()" in NewOperation
double d = operation.Do();

Operation operation_ = operation;

// Will call "int Do()" in Operation
int i = operation_.Do();
abstract
Abstract classes are classes that only serve as templates and you can not initialize an object of that type. Otherwise it is just like an ordinary class.
There may be abstract members too. Abstract members are members of abstract classes that do not have any implementation. They must be overridden by the class that inherits the member.
abstract class Mammal
{
    public abstract void Walk();
}

class Human : Mammal
{
    public override void Walk()
    {

    }

    ...
}
sealed
The sealed modifier can be combined with the others as an optional modifier for classes to make them uninheritable.
internal sealed class _AAA
{

}

Comments