Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, December 31, 2016

C # Interfaces



To those are working in IT may be technical or not , in their life they will come across term interface,
and almost every one know what does it mean i.e definition syntax and how to and when to use. Most of the coding guys say it  "as classes do not support multiple inheritance and it will be possible in interfaces"  and we say they don't have implementation only definition and no declaration.


So lets learn after what we know,


Interfaces are considered as a contract consisting of properties and methods  and events, when a class implementing the interface it makes a commitment i.e fulfilling contract by implementing ALL(properties also) its interface members 
By default all  members are public , we cannot specify access modifiers to interface members 

An interface is similar to PURELY abstract class i.e class containing all abstract members (i.e no implementation)



Benefits of using interface is that code can be easily Maintainable

When your GetPeople implementation changes i.e if it returns List<Person> then again you need to change your implementation in 1st case as we get compilation error
but we did not have to change the interface implemented code, thats because Person[] and List<Person> both Implement IEnumerable

so when we are coding to the abstraction we don't care about the specific class coming back.All we do is its is a class that fulfills the contract , which makes our code more resistant .As every collection in .NET implements IEnumerable our repository may be stack, queue or whatever ...everything will work exactly without any change.. SO thats thing about programming to abstraction if the underlying implementation changes our code doesn't care 

We can also strongly type the collection like IEnumerable<Person>

So when we are programming to abstraction , we're adhering to a contract , but we don't care about implementation details i.e Get the functionality you need and not bothering about the specific type.

How:

we want code that is extensible that can respond quickly to new requirements , if we come up with a contract that the core application can use then we can plug in any number of different implementations that adhere to that contract 

Improving extensibility :
 For  example say you are getting data from repository using Service...
Generally we will use repository pattern in coding i.e BL repository (May be using Services, or CSV or SQL Connection).. this may vary so what we do is.. create an interface with what is required i.e functionalities so we create an interface with CRUD operations we want and then we use it in presentation layer .. so that ur UI doesn't care about actual implementation whether using services or csv or what ever no change in using that ()

i.e what ever the class obeying the interface contract can be used

Sample service repo :


Without using interfaces: we have to create objects for each type and use them ..redundant code ... so when we care  only about operations(features provided) and don't bother about underlying implementation it really helps in extending your code with out actually disturbing the usage/Consuming in your  presentation layer


** When an interface is implemented in a class , its access specifier should be public only otherwise it'll throw error
** IF you have Interface I1 with Method M1 and Interface I2 with M2 and when you inherit I2 in your class then you have to provide implementation for both M1 and M2.

Explicit Interface Implementation 





so why explicit implementation? 

If you have 2 interfaces to be implemented you can have it with single method also but why explicity defining / implementing them as shown above?
Because when two interfaces you have inherit have same method name but different return types then this explicit implementation is mandatory

for example when you inherit IEnumerable<T> then you can see as (internally IEnumerable<T> inherits IEnumerable) then you have to provide implementation for both GetEnumerator and GetEnumerator<T>

Explicit implementation of interface member should not have Access modifier  

Program to an abstraction rather than a concrete type i.e -->Program to an interface rather than a concrete class


Actual Usage:

So as we have seen above when we use interface we actually bother about the functionality provided and not the type which is serving .. so we have minimal change in presentation layer but we have to pass the type we want to connect and get data like in prev example either csv or sql or whatever

So we have to pass from UI which type you would like to and your factory class will instantiate that class and return that object (Interface )

1.So how can we make zero impact on UI , not even passing type
2.In the example what ever may be the type either from service / csv / sql we have to load all three assemblies as wen instantiate them in factory class

Suppose if we  get new type then we have to change UI and also add reference to our repo factory class project build it and then change the repo factory ...


We can avoid all above using Dynamic Loading

i.e no need to pass type from UI or load assemblies

1.We wont pass from UI we'll pick from configuration key of web config
2.We manually put the dll in bin folder of project to pick them which will actually happen when we add a reference (we can have a post build event for that or if you dont want to give new build you can directly place them in bin folder )


like wise for others also we can enable what ever configuration you want to use
To dynamically load the dlls or assemblies



So now no need to change any code level implementation nor give any new build...
Just Change the web.config with new app settings and place the dlls of your new implementation type in bin folder... bang!! ... done with ZERO code level impact or change


Conclusion: So, on a final note what we all to remember is interface is commitment and contract :-)

Sunday, October 25, 2015

C# : Part1 [Basics]

In this article , today we gonna look at some of the pre-defined keywords used in C#, access specifiers, value types & reference types and other basic concepts

Intro:
--> C# has been registered in   international recognized standards organisation where we can see specs

-->The C# code can be written in notepad and compiled using inbuilt compiler through command line, we can see C Sharp Compiler(csc.exe) in below path 
     C:\Windows\Microsoft.NET\Framework\v4.0.30319
We can compile our code using this compiler in following way
          C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe yourfile.cs
This produces executable file of your code , you can see the yourfile.exe by giving dir command and now you can exec that file by giving yourfile.exe 

We do have String[] args param in Main methods , we can pass parameters to it from command line  after your exe file

-->When Projects are added to Solution explorer each proj will be converted to an assembly i.e either as a dll or an executable file. 

Class:
They  define types which is understandable by assembly, which contains
 -->Properties,Fields,..i.e data the state an object can hold
 -->Behovior : Methods 
We can define accessibility of members in class

Objects are Instances of a type: 
We can create multiple instances, each instance holds different state, each instance has same behavior

Classes create reference types, Objects are stored on heap. Variables reference the object instance.
Default classes inherit  System.Object class

Employee e1 = new Employee();

e1 is referencing Employee object on heap but its not forever , we can again have i.e another employee object

e1 = new Employee();
e1.Name = "Sudhir";

Imp note here is we can have multiple variables referencing same object
eg:
Employee e2; //we are not initializing to new Employee object
e2=e1; // e2 is referencing same object that is created and assigned to  e1, we can check this by object.ReferenceEquals(e1, e2); which will return true as both reference same memory

e2.Name = "Paturu";

When we print e1.Name we still get "Paturu" because e1 and e2 both are referencing same object on heap

Mutable vs Immutable:

AS said most reference type objects are Mutable i.e can be changed at any point of time it will not create another object or memory on heap but where as  string is immutable even though it is reference type

string s1 = "Hi";

string s2 = "Hello";

s2=s1;   // Same as above class example when we check object.ReferenceEquals it will return true
but when s1="Sudhir"; and check now Object.ReferenceEquals of s1 & s2 it will return false because string is Immutable(its State cannot be changed) it will now reference other memory location in heap , so reference will be changed hence now s1 will reference one memory and s2 refer other 

Inheritance: Ability to define a class that inherits state and properties and behaviour from other calsses.
    This is one approach to reuse code (But not to reuse code we use inheritance )
Encapsulation : Ability to hide details inner workings of a class

Polymorphism: Plays role with inheritance to reuse code with extensibility mechanism where by customizing class that is inheriting behaviour for other class

Access Modifiers: 

Public : Can apply to class or member of a class and it creates open access , classes declared public can be  accessed from other projects implied they should be added reference

Protected : Can be applied to Members  of a class , access is limited to the class that declaring the protected member and any derived class(inherited class). Only when inherited (Can be accessed when inherited both in current assembly and outside also) but where as when we create instance of that class we cannot access it.

Internal : Can be applied to a class or Member of a class , where access is limited to current assembly .
This is default accessibility of a class in C# . i.e only internal classes can be referred inside the application or project even though this is referred in another project we cannot access such classes because it is out if assembly 

Protected Internal : Applied to members of class where there access varies in current assembly and when referred in other projects
1.When in current assembly it acts as internal i.e when we create instance of class we can access it.
2.Outside the assembly it can be accessed but only when from derived class i.e when it is inherited.i.e acts as protected outside the assembly.

private : Can be applied to members Default accessibility of a member, access limited to the class

Abstract:
This  can be applied class  and can also applied to methods, properties all members
 Abstract class cannot be instantiated , i.e we cannot use new operator to create object i.e it is designed to use it as base class , only can be inherited i.e only for reuse 
The members in base class does not have implementation jus declaration 

If abstract classes have abstract methods then such methods need to be implemented in derived class  , we can implement using a override keyword

Virtual : This  keyword creates  virtual members, where we can change the behaviour of member if required in derived class using Override keyword , while overriding we may sometimes need to implement that original definition with some extra features then we can use base.thatMethod(); inside override before your custom implementation

Static : Are members of the type, Cannot invoke the member through object instance , Cannot instantiate a static class eg: Math.Pi, Colors.Red etc  . Only one copy is maintained through out once declared.


Sealed : Sealed classes cannot be inherited (To prevent extensibility or misuse, for security purposes)
eg:  System.String is sealed class we cannot inherit it. (Improves performance)

In the same way for members: When a method is declared as virtual we can override with sealed keyword so that when this child class is inherited by some other class then we cannot override that method.

Partial :  This keyword is used to split class definition across multiple files. We can also have  partial methods just like classes , partial methods cannot have implementation jus like abstract methods. we can define them in other file of this  partial class.

Reference Types:
Multiple variables can point to same object , single variable can point to multiple objects over its lifetime i.e (Mutable ..its sate can be changed ).
--> Objects are allocated on the heap by new operator  (Value type variables will be stored on stack.)


Value Types:
Variables hold value, No pointers or references, Immutable . No objects are allocated on heap - lightweight .
Many built in primitives are value type only allowed to store less data not more than 16 bytes .. When we copy a variable x of  Int32 to variable of y Int32 then entire whole 32bits are copied which causes performance issues

Struct : These are also Value type , Like a class we add properties,fields and methods but we cannot inherits these structs and should be less than 16 bytes and ,must be primitive data types

Parameters:  In C# all parameters always pass by value (default), where as reference types pass a copy of the reference i.e changes are propagated to caller.

   eg:
class Dog
 {
    public string name { get; set; }

 }
 static void Main(string[] args)
 {
   Dog obj = new Dog();
   obj.name = "Main Obj";
   Console.WriteLine("Original :" + obj.name);
   TestingParams(obj);
   Console.WriteLine("After Calling Method : " + obj.name);
   Console.Read();
 }

public static void TestingParams(Dog objDog)
  {
    objDog.test = "Modified";

  }

Here, second time we will get o/p as Modified  even though base object isn't modified in main method.It implies for reference types params changes effect caller object as they pass reference not actual value.

Note: This is not applicable for string because its immutable as defined above.

Parameter Keywords :  For those types where we cannot change values of caller method i.e Value types we can use keywords 'ref' and 'out'

Both are used for same purpose , but major difference is  when you declare with 'ref' in the child method it will check whether that is initialized with some value in parent method because it will be used in chid method where as when declared as 'Out' no need to initialize in parent method.

eg: 
public static void Method1()
 {
   string Name;
   int Id;
   Dog obj = new Dog();
   obj.Name = "alpha";
   ChildMethod(ref Name, out Id, obj)  // Here we get obj.Name as Beta
   childMethod2(obj); // Here Obj.Name will not be Test Dog . If we like to change                      the base object then we need to pass its reference like ref obj

        }

public void childMethod(ref string Name, out int id, Dog objDog)
  {
     id = 0;    // we have to define here otherwise we get error as  out param must                     be declared before control leaves current  method   
     objDOg.Name = "Beta";

   }


public void childMethod2(Dog objDog)
 {
   objDog = new Dog(); // A new instance is declared no more points to same                     reference pointed by object in main  method
   objDog.Name = "TestDog";

 }


params:  when you like to send a set of values of same type then we declare an array and send it , where as params keyword provides flexibility to pass by values (any number dynamically)

eg : 
public void Testing(int[] values)
 {

 }

To send integers you want to play we pass integer array or something like  Testing(params int[] values);
where as when we declare method with params keyword as below we can have flexibility of passing values directly like Testing(2,3); or Testing(4,5,6,7); or Testing(9);
public void Testing(params int[] values)
 {


 }


enum:  Creates a value type set of named constants (Why : To Improve Readability)
--> Underlying datatype is  int by default  
By default value in an enumeration start with zero , however we can explicitly define the behaviour 

Arrays: Sample data structure for managing  a collection of variables , everything inside  will have same datatype , indexed from Zero . The index of item which is not in array will be '-1'.
Array inherits from many interfaces like Iclonable, IList etc so in the params instead a array variable we can also use IList or any interface (It will take any element that implement IList interface)