Showing posts with label Class. Show all posts
Showing posts with label Class. Show all posts

What are Access Modifiers in C#?

Access modifiers are keywords used to specify the declared accessibility of a member or a type. An access specifier precedes the rest of a members type specification.

Public – When a member of a class is modified by the public specifier, that member can be freely accessed by code defined outside of its class. It marks a member as accessible from an object variable as well as any derived classes.

Private – When a member of a class is specified as private, that member can be accessed only by other members (methods) defined by its class. In C#, all members are private by default (if no access specifier is used, a class member is private by default). Enum and interface are public by default.

Protected – When a member of a class is specified as protected, that member is private to their class, but still can be inherited and accessed by a derived class. Protected methods, however, are not accessible from an object variable.

Internal – The internal modifier declares that a member is accessible throughout all files (by any type) in an assembly, but not outside the assembly. In simplified terms, a member marked internal is known throughout a program, but not elsewhere.

The internal modifier can be applied to classes and members of a class, structures and members of structures, interface and enumeration declarations.

Protected Internal – A member declared protected internal access is accessible within its own assembly or types derived from the defining class in the current assembly. The protected internal access level can be given only to class members.

Destructor

Destructors are used to destruct instances of classes. It can only be used with classes and not with structs. A class can only have a single destructor, which neither can be called nor inherited or overloaded. They are invoked automatically as and when determined by the garbage collector. A destructor cannot have access modifiers or parameters. 

The destructor implicitly calls the Object.Finalize method on the object's base class. This means that the Finalize method is called recursively for all of the instances in the inheritance chain, from the most derived to the least derived. 

The destructor is called as and when determined by the garbage collector. The garbage collector checks for objects that are no longer being used by the application. These objects are considered eligible for destruction and the GC reclaims their memory. Destructors are also called when the program exits.

Related Post: Constructors

Constructors

Constructors (Instance Constructor)

Constructors are used to create and initialize instances. If the class does not have a constructor, a default parameterless constructor is automatically generated and the default values are used to initialize the object fields (for example, an int is initialized to 0).

When a class constructor is invoked a new object is created:

Point myPoint = new Point();

The class constructor can invoke the constructor of the base class through the initializer:

public Cylinder(double radius, double height) : base(radius, height)
{
}

The class constructor can also invoke another constructor from the same class by using the keyword this:

public Point() : this(0,20)
{
}

In C#, functions are not virtual by default but (aside from constructors) can be explicitly declared as virtual.

Struct constructors

Struct constructors are similar to class constructors, except for the following differences:
  • Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
  • A struct cannot have an initializer in the form : base (argument-list).

Static Constructors
  • A given class (or structure) may define only a single static constructor.
  • A static constructor executes exactly one time, regardless of how many objects of the type are created.
  • A static constructor does not take an access modifier and cannot take any parameters.
  • The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller.
  • The static constructor executes before any instance-level constructors.

Related Post:
Destructor

Explain Classes in detail

A class is the blueprint from which individual objects are created. This blueprint describes the state and behaviour that all the objects of the class share.  A class may be composed of any number of members (such as properties, methods, and events) and data fields. A class has both an interface and a structure.

Concrete classes


A concrete class is a class that can be instantiated.

Abstract Classes


Abstract classes are intended to define common behaviours for derived types. An abstract class is designed only as a parent class from which child classes may be derived. Abstract classes cannot be instantiated. They are often used to represent abstract concepts or entities. The incomplete features of the abstract class are then shared by a group of subclasses which add different variations of the missing pieces. The behaviours defined by such a class are "generic" and much of the class will be undefined and unimplemented. Before a class derived from an abstract class can become concrete, it must implement all of the abstract methods in parent classes.

Abstract Method


An abstract method contains no body and is, therefore, not implemented by the base class. Thus, a derived class must override it. An abstract method is automatically virtual, and it is an error to use virtual and abstract together. The abstract modifier can only be used on normal methods. It cannot be applied to static methods. Properties and indexers can also be abstract.

When a derived class inherits an abstract class, it must implement all of the abstract methods in the base class. If it doesn't  then the derived class must also be specified as abstract. Thus, the abstract attribute is inherited until such time that a complete implementation is achieved.                                                                                              

Sealed classes


A sealed class cannot be used as a base class. For this reason, it also cannot be an abstract class. Sealed classes are primarily used to prevent derivation. They add another level of strictness during compile-time, improve memory usage, and trigger certain optimizations that improve run-time efficiency.  

Partial classes 


The partial keyword allows the class, struct, method or interface to span across multiple files. Partial classes are classes that can be split over multiple definitions (typically over multiple files), making it easier to deal with large quantities of code. At compile time the partial classes are grouped together, thus logically make no difference to the output. A primary benefit of partial classes is allowing different programmers to work on different parts of the same class at the same time. They also make automatically generated code easier to interpret, as it is separated from other code into a partial class. 

Static Classes      


When a class is defined as static, it cannot be instantiated using the new keyword, and it can contain only static members or fields. 

Static classes are used to create data and functions that can be accessed without creating an instance of the class. Static classes can be used when there is no data or behavior in the class that depends on object identity.

It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework Common Language Runtime (CLR) when the program or namespace containing the class is loaded


Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state. The System.Console and System.Math classes are good examples of static classes.
The main features of static classes are: 

  • They only contain static members.
  • They cannot be instantiated. 
  •  They are sealed.
  • They cannot contain Instance Constructors.

Static Members

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called.

Static methods can be overloaded but not overridden. A field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.

C# does not support static local variables (variables that are declared in method scope).

Difference between class and struct in C# .Net

1. Classes are reference types and structs are value types. Since classes are reference type, a class variable can be assigned null. But we cannot assign null to a struct variable, since structs are value type.
2. When you instantiate a class, it will be allocated on the heap. When you instantiate a struct, it gets created on the stack.
3. You will always be dealing with reference to an object (instance) of a class. But you will not be dealing with references to an instance of a struct (but dealing directly with them).
4. When passing a class to a method, it is passed by reference. When passing a struct to a method, it’s passed by value instead of as a reference.
5. You cannot have instance Field initializers in structs, but classes can have.
Example:
class MyClass
{
int iVar = 10; // no syntax error.
public void MyFun( )
{
// statements
}
}
struct MyStruct
{
int iVar = 10; // syntax error.
public void MyFun( )
{
// statements
}
}
6. Classes can have explicit parameterless constructors, but structs cannot have an explicit declaration of a parameter less constructor. A struct always has a built-in public default constructor. This means that a struct is always instantiable whereas a class might not be since all its constructors could be private.
7. A structs static constructor is not triggered by calling the structs default constructor. It is for a class.
8. Classes support inheritance. But there is no inheritance for structs (structs don’t support inheritance, polymorphism).
9. Since struct does not support inheritance, access modifier of a member of a struct cannot be protected or protected internal.


11. A class is permitted to declare a destructor, but a struct cannot have a destructor. A destructor is just an override of object.Finalize in disguise, and structs, being value types, are not subject to garbage collection.
12. Classes are used for complex and large set data. structs are simple to use.

Difference between class and interface in C#

A C# Class Considered being the primary building block of the language. What I mean by the primary building block of the language is that every time you work with C# you will create Classes to form a program. We use Classes as a template to put the properties and functionalities or behaviors in one building block for some group of objects and after that we use that template to create the objects we need.

A class can contain declarations of the following members:

Constructors, Destructors, Constants, Fields, Methods, Properties,Indexers, Operators, Events, Delegates, Classes, Interfaces, Structs

An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface. A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.

An interface can inherit from one or more base interfaces. When a base type list contains a base class and interfaces, the base class must come first in the list.


interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation: 
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}