Friday, May 31, 2013

Internal Access Modifiers

Members declared with internal access modifiers can be accessed from within the same assembly in which the member is defined.  These members can also be accessed from other classes which reside in the same assembly.

The following example defines an internal variable
strInternalName.

Protected Access Modifiers

Members declared with protected access modifiers can be accessed from within the class and from any class which derives from the class which defines the members. These members are not visible to external classes which do not derive from the underlying class.

The following example defines a protected variable
strProtectedName.

Public Access Modifiers

This is the most lenient of all the access modifier, any member of the class which is defined public can be accessed from anywhere inside or outside of the class. Members defined with this modifier provide no restriction in getting or setting the values.

The following example defines a public variable
strPublicName.

Private Access Modifiers

This is the most restrictive access modifier, any member of the class which is defined private cannot be accessed from outside the class, these members are visible only within the class, trying to access these members outside the class will result in a compilation error.

The following example defines a private variable
strPrivateName.

What are Access Modifiers?

Access modifiers are keywords which are used to define the scope / accessibility of class members. Access modifier keywords should be added in front of the variable or function to define its scope.

The following are the 4 access modifiers available in C# .Net

Auto-Implemented Properties

We have seen many types of properties so far, you would have notices that defining a simple get/set property involves many lines of code. A simple private variable with a public property definition needs about 10 lines of code, if this is the case then complex class with many properties will have hundreds of lines of code. Auto Implemented properties help us to overcome this by simplifying property definition of simple properties.

Auto-Implemented Properties were introduced in .Net 3.0 to simplify property definition; the following example defines a 2 auto implemented properties Name and Age with just 2 lines of code.

Static Properties

Static members of a class are those which can be accessed without creating an instance of the containing class, similarly static properties can be assessed directly by prefixing the property name with the class name and a dot (.). Static properties should have the keyword static mentioned in their definition.

In the following example we will define a static property and access the same directly without creating an instance of the class.

Abstract Properties

Abstract Properties are similar to Interface Properties, Abstract Properties are those which are defined in an Abstract class, similar to Interface Properties they do not have any definition, we just need to define the get {} and/or set {} accessors.

The class which inherits the abstract class will use the property and define the get {} and/or set {} accessors in the derived class.

The following example defines an abstract class with an abstract property.

Thursday, May 30, 2013

Interface Properties

Interface properties are those which are defined in the interface and implemented in the class which implements the interface. Interface properties do not have a definition, they just specify the name of the property and its accessibility Read-Write, or Read-Only or Write-Only.

The following example defines an Interface Property Name in the interface IEmployee

Properties with Validation

In general properties have a get {} and set {} accessor which is used to get and set the values of the underlying private member in the class, these properties just make sure that the values which is being set from the external source matches the expected data type of the underlying private member. Apart from this they do not perform any other validation.

There are specific where the value to be set to a private member should satisfy certain business validations, since the member is private there is no way to set the value directly from external sources, the only way to set a value to the member is through the set {} accessor, we can perform a set of validations in the set {} accessor before assigning values to the variable.

In the following example we impose a simple validation to the UserName property, the value assigned to the property should be a string of length greater than or equal to 8, else an exception should be thrown.

Write only Properties

As the name suggests write-only properties are those which can be assigned from external classes but the value cannot be read from any external class.

In general a property has get {} and set {} accessors, to create a write-only property we just need to define the set {} accessor for the property without the get {} accessor.

The following example defines a write-only property for the private variable strName

Read only Properties

As the name suggests read-only properties are those which can be consumed by external classes but cannot be reset by any operation external to the class.

In general a property has get {} and set {} accessors, to create a read-only property we just need to define the get {} accessor for the property without the set {} accessor.

The following example defines a read-only property for the private variable strName

Wednesday, May 29, 2013

What is a Property?

Object oriented programming languages support encapsulation, which is also called as data hiding. Encapsulation is hiding the private variables of a class from the external world, if we are hiding the members then how do we get and set the values of these members? It is when Properties become significant.

Properties define get and set assessors which can be used to get and set values of private variables in a class.

Class Vs Structs

Both Classes and Structs are constructs in C# which are used to create custom complex types by encapsulating a set of basic types and logic. Though they are used to create custom types there are some underlying differences between the two, the following are some of the differences between classes and structs.

Tuesday, May 28, 2013

Value Type Vs Reference Type

In .Net any variable / object falls under one of the types Value Type or Reference Type, by default structs are value type and classes are reference type. 

The following are some of the key difference between value type and reference type variables / objects.

Reference Type

Reference Type objects are those which have a do not have a separate memory segment instead they have a pointer connecting the variable and the actual object, when a reference type variable is copied to another reference type variable, both the variables share the same memory segment and changes done to one of the variable will affect the value of the other, since there is only one underlying object and 2 pointer pointing to the same object.

All Reference Type objects are implicitly derived from System.Object

Value Type

Value Type variables are those which have a separate memory segment allocated for them, when a value type variable is copied to another value type variable each variable has its own memory segment and changes done to one of the variable does not affect the value of the other.

All value type variables are implicitly derived from System.ValueType

OUT vs REF Parameters

OUT and REF parameters are almost similar, both are used to return additional values from a function to the code which is calling the function. However there are some difference between the two, the following are the some of the key differences between the OUT and REF parameters.

Out parameters are declared by adding the keyword out in front of the parameter.

REF Parameter

REF parameters are parameters which are passed between the calling function and the function being called, we need to declare and initialize the parameters in the calling method, their values will be re-assigned in the actual function and returned back to the calling function.

REF parameters are declared similar to the normal parameters by adding a ref keyword in front of the parameter as follows.

OUT Parameter

OUT parameters are parameters which are passed back from a function to the calling function or method, it is good enough to declare the parameters in the calling method they need not be initialized in the calling class, instead their values will be assigned in the function which is returning the out parameters.

OUT parameters are declared similar to the normal parameters by adding an out keyword in front of the parameter as follows.

Constants

As the name suggests Constants are a type of class members whose value is defined at the time of writing the program and remain constant forever, the values of constants cannot be changed at runtime, the values of a constant defined in a class will remain same for every instance that is created from the class.

Constants are declared using the
const keyword as follows.

Monday, May 27, 2013

Anonymous Types

Anonymous types allow us to define variables and classes dynamically at runtime without having to declare them beforehand. The following example creates a string variable MyName dynamically at runtime without any specific declaration.

    var MyName = "Test Name";
    Console.WriteLine(MyName.GetType());

When this code executes the output will be as follows

Nested Classes

As the name suggests, nested classes are classes which are defined within an outer parent class. The following example creates a nested class called NestedClass which is encapsulated in the outer class called OuterClass.

Destructors

Destructors are used to free unused resources and release memory used by the resources. Destruction of Managed objects are handled by the Garbage collector in the .Net Framework, we can use the destructor to release any unmanaged resources like Network connectivity, database connections etc and release the resources.

The signature of the destructor is similar to a constructor, it shares the same name of the class, the only difference is that we add a ~ symbol in front of the method name to denote that this is a destructor.

The following example defines a destructor for the CEmployee class

Constructors

Constructors are methods of a class which get executed automatically when an instance of a class is created. The constructor method name should be same as the class name.

The following example defines a simple constructor for the class CEmployee

Sunday, May 26, 2013

What is a Struct?

Structs can be used to define custom types, which are build using a combination of the primitive types like int, string etc. For example we can define an Employee Struct which can hold details of the employee id, name, address etc in individual types like int, string etc.

Structs are value types while classes are reference types, which means that every instance of the Struct is completely independent and have their own set of values. If a struct instance A is assigned to struct instance B then both A & B have their own memory and have an independent set of value, hence any change to instance A will not affect instance B.

The below example defines a simple Struct which contains an integer id and a string name representing an employee details.

Saturday, May 25, 2013

What is an Object?

An object is an instance or representation of a class. Objects are the building blocks of Object Oriented Programming, objects give life to classes and structs. Classes are mere definition of a model,  the model gets activated only when an object is created out of the class.

We can create multiple instances of objects from a single class definition; each object is unique and can hold its own set of values. The fields/properties of an object are used to set/get values to the object while the methods of the object are used to perform some operation on the object.


Let us consider the same Calculator class which we defined in the post What is a Class?, here we shall create an instance of the class, set values to the fields and invoke the methods of the object to see how it operates.

    Calculator objCalculator = new Calculator();
    int nResult = objCalculator.Add(5, 6);
    txtResult.Text = nResult.ToString();

Here objCalculator is the object which represents the class Calculator, the object objCalculator invokes the Add() method of the class and passes values to the method. The object performs the calculation which is defined in its base class definition and returns the result of the calculation, which is captured and displayed in the textbox txtResult in the client application.

What is a Class?


A Class is the basic definition or template of an object, a class defined the properties, methods, events etc of an object. A class is used to represent a real world object/model. For example a calculator can be represented using a Calculator class, the Calculator class defines the properties of a Calculator like input Numbers, operations etc.

A Calculator class just defines the properties and methods of an object, a class does not hold any values of these properties, and to assign values to these we should create an object which represents an instance of the class.

The following example shows a simple Calculator class defined in C#

What is OOP?

OOP stands for Object Oriented Programming, as the name suggests OOP is a type of programming pattern which is governed by OOP principles.

Prior to the introduction of OOP, programming was done using structural programming languages like Fortran, Pascal etc. In structural programming languages the order of execution of the program is sequential, i.e execution happens line by line starting from the first line till the last line in the program is completed.