Specializations

Monday, November 4, 2013

c# basics


OOPS

What is Object Oriented Programming?
It is a problem solving technique to develop software systems. It is a technique to think real world
in terms of objects. Object maps the software model to real world concept. These objects have
responsibilities and provide services to application or other objects.
What’s a Class?
A class describes all the attributes of objects, as well as the methods that implement the behavior of
member objects. It’s a comprehensive data type which represents a blue print of objects. It’s a template
of object.
What’s an Object?
It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects are
members of a class. Attributes and behavior of an object are defined by the class definition.
What is the relation between Classes and Objects?
They look very much same but are not same. Class is a definition, while object is a instance of the class
created. Class is a blue print while objects are actual objects existing in real world. Example we have
class CAR which has attributes and methods like Speed, Brakes, Type of Car etc. Class CAR is just a
prototype, now we can create real time objects which can be used to provide functionality. Example we
can create a Maruti car object with 100 km speed and urgent brakes.

What is Abstraction?
It allows complex real world to be represented in simplified manner. Example color is abstracted to
RGB. By just making the combination of these three colors we can achieve any color in world.It’s a
model of real world or concept.

What is Encapsulation?
It is a process of hiding all the internal details of an object from the outside world.
What is Object lifetime?
All objects have life time.Objects are created ,and initialized, necessary functionalities are done and
later the object is destroyed. Every object have there own state and identity which differ from instance to
instance.
What is Association?
This is the simplest relationship between objects. Example every customer has sales. So Customer object
and sales object have an association relation between them.
What is Aggregation?
This is also called as composition model. Example in order to make a "Accounts" class it has use other
objects example "Voucher", "Journal" and "Cash" objects. So accounts class is aggregation of these three
objects.
What is Polymorphism?
When inheritance is used to extend a generalized class to a more specialized class, it includes behavior of
the top class(Generalized class). The inheriting class often implement a behavior that can be somewhat
different than the generalized class, but the name of the behavior can be same. It is important that a given
instance of an object use the correct behavior, and the property of polymorphism allows this to happen
automatically.
What are abstract classes?
Following are features of a abstract class :-
1. You can not create a object of abstract class.
2. Abstract class is designed to act as a base class (to be inherited by other classes). Abstract class is a
design concept in program development and provides a base upon which other classes are built.
3. Abstract classes are similar to interfaces. After declaring an abstract class, it cannot be instantiated on
its own, it must be inherited.
4. In VB.NET abstract classes are created using "MustInherit" keyword.In C# we
have "Abstract" keyword.
5. Abstract classes can have implementation or pure abstract methods which should be implemented in
the child class.
What is a Interface?
Implementing a interface it says to the outer world, that it provides specific behavior. Example if a
class is implementing Idisposable interface that means it has a functionality to release unmanaged
resources. Now external objects using this class know that it has contract by which it can dispose unused
unmanaged objects. Single Class can implement multiple interfaces.
If a class implements a interface then it has to provide implementation to all its methods.
What is difference between abstract classes and interfaces?
Following are the differences between abstract and interfaces :-
1. Abstract classes can have concrete methods while interfaces have no methods implemented.
2. Interfaces do not come in inheriting chain, while abstract classes come in inheritance.
What is a delegate?
Delegate is a class that can hold a reference to a method or a function. Delegate class has a signature and
it can only reference those methods whose signature is compliant with the class. Delegates are type-safe
functions pointers or callbacks.

Do events have return type?
No, events do not have return type.
Can event’s have access modifiers?
Event’s are always public as they are meant to serve every one registering to it. But you can access
modifiers in events.You can have events with protected keyword which will be accessible only to

inherited classes.You can have private events only for object in that class.
Can we have shared events?
Yes, you can have shared event’s. Note: Only shared methods can raise shared events.
What is shadowing?
When two elements in a program have same name, one of them can hide and shadow the other one. So in
such cases the element which shadowed the main element is referenced.
What is the difference between Shadowing and Overriding?
Following are the differences between shadowing and overriding :-
1. Overriding redefines only the implementation while shadowing redefines the whole element.
2. In overriding derived classes can refer the parent class element by using "ME" keyword, but in
shadowing you can access it by "MYBASE"
What is the difference between delegate and events?
Actually events use delegates in bottom. But they add an extra layer on the delegates, thus forming the
publisher and subscriber model.
As delegates are function to pointers they can move across any clients. So any of the clients can add
or remove events, which can be pretty confusing. But events give the extra protection by adding the
layer and making it a publisher and subscriber model. 212 Just imagine one of your clients doing this
c.XyzCallback = null This will reset all your delegates to nothing and you have to keep searching where
the error is.
If we inherit a class do the private variables also get inherited?
Yes, the variables are inherited but can not be accessed directly by the class interface
What are the different accessibility levels defined in .NET?
Following are the five levels of access modifiers :-
1. Private : Only members of class have access.
2. Protected :-All members in current class and in derived classes can access the variables.
3. Friend (internal in C#) :- Only members in current project have access to the elements.
4. Protected friend (protected internal in C#) :- All members in current project and all members in
derived class can access the variables.
5. Public :- All members have access in all classes and projects.
Can you prevent a class from overriding?
If you define a class as "Sealed" in C# and "NotInheritable" in VB.NET you can not inherit the class
any further.
What is the use of "MustInherit" keyword in VB.NET?
If you want to create a abstract class in VB.NET it’s done by using "MustInherit" keyword.You can not
create an object of a class which is marked as "MustInherit". When you define "MustInherit" keyword
for class you can only use the class by inheriting.
Do interface have accessibility modifier?
All elements in Interface should be public. So by default all interface elements are public by default.
What are similarities between Class and structure?
Following are the similarities between classes and structures :-
1. Both can have constructors, methods, properties, fields, constants, enumerations, events, and event
handlers.
2. Structures and classes can implement interface.
3. Both of them can have constructors with and without parameter.
4. Both can have delegates and events.
What is the difference between Class and structure’s?
Following are the key differences between them :-
1.Structure are value types and classes are reference types. So structures use stack and classes use heap.
2. Structures members can not be declared as protected, but class members can be. You can not do
inheritance in structures.

3. Structures do not require constructors while classes require.
4.Objects created from classes are terminated using Garbage collector. Structures are not destroyed using
GC.
What does virtual keyword mean?
They are that method and property can be overridden.
What are shared (VB.NET)/Static(C#) variables?
Static/Shared classes are used when a class provides functionality which is not specific to any instance.
In short if you want an object to be shared between multiple instances you will use a static/Shared class.
Following are features of Static/Shared classes :-
1. They can not be instantiated. By default a object is created on the first method call to that object.
2. Static/Shared classes can not be inherited.
3. Static/Shared classes can have only static members.
4. Static/Shared classes can have only static constructor.
What is Dispose method in .NET?
NET provides "Finalize" method in which we can clean up our resources. But relying on this is not
always good so the best is to implement "Idisposable" interface and implement the "Dispose" method
where you can put your clean up routines.
What is the use of "OverRides" and "Overridable" keywords?
Overridable is used in parent class to indicate that a method can be overridden. Overrides is used in the
child class to indicate that you are overriding a method.
Where are all .NET Collection classes located?
System.Collection namespace has all the collection classes available in .NET.
What is ArrayList?
Array is whose size can increase and decrease dynamically. Array list can hold item of different types.
As Array list can increase and decrease size dynamically you do not have to use the REDIM keyword.
You can access any item in array using the INDEX value of the array position.
What’s a HashTable?
You can access array using INDEX value of array, but how many times you know the real value of
index. Hashtable provides way of accessing the index using a user identified KEY value, thus removing
the INDEX problem.
What are queues and stacks?
Queue is for first-in, first-out (FIFO) structures. Stack is for last-in, first-out (LIFO) structures.
What is ENUM?
It’s used to define constants.
What is Operator Overloading in .NET?
It allows us to define/redefine the way operators work with our classes and structs. This allows
programmers to make their custom types look and feel like simple types such as int and string. VB.NET
till now does not support operator overloading. Operator overloading is done by using the "Operator"
keyword. Note:- Operator overloading is supported in VB.NET 2005.
What is the significance of Finalize method in .NET?
.NET Garbage collector does almost all clean up activity for your objects. But unmanaged resources
(ex: - Windows API created objects, File, Database connection objects, COM objects etc) is outside the
scope of .NET framework we have to explicitly clean our resources. For these types of objects .NET
framework provides Object. Finalize method 218 which can be overridden and clean up code for
unmanaged resources can be put in this section.
Why is it preferred to not use finalize for clean up?
Problem with finalize is that garbage collection has to make two rounds in order to remove objects
which have finalize methods. Below figure will make things clear regarding the two rounds of garbage
collection rounds performed for the objects having finalized methods. In this scenario there are three
objects Object1, Object2 and Object3. Object2 has the finalize method overridden and remaining

objects do not have the finalize method overridden. Now when garbage collector runs for the first time
it searches for objects whose memory has to free. He can see three objects but only cleans the memory
for Object1 and Object3. Object2 it pushes to the finalization queue. Now garbage collector runs for
the second time. He see’s there are no objects to be released and then checks for the finalization queue
and at this moment it clears object2 from the memory. So if you notice that object2 was released from
memory in the second round and not first. That’s why the best practice is not to write clean up Non.NET
resources in Finalize method rather use the DISPOSE.
How can we suppress a finalize method?
GC.SuppressFinalize ()
What is the use of DISPOSE method?
Dispose method belongs to IDisposable interface. We had seen in the previous section how bad it can be
to override the finalize method for writing the cleaning of unmanaged resources. So if any object wants
to release its unmanaged code best is to implement 220 IDisposable and override the Dispose method of
IDisposable interface. Now once your class has exposed the Dispose method it’s the responsibility of the
client to call the Dispose method to do the cleanup.
How do I force the Dispose method to be called automatically, as clients can forget to call Dispose
method?
Call the Dispose method in Finalize method and in Dispose method suppress the finalize method
using GC.SuppressFinalize. Below is the sample code of the pattern. This is the best way we do clean
our unallocated resources and yes not to forget we do not get the hit of running the Garbage collector
twice. Note:- It will suppress the finalize method thus avoiding the two trip. Public Class ClsTesting
Implements IDisposable Public Overloads Sub Dispose()Implements IDisposable.Dispose ' write ytour
clean up code here GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose() End
Sub End Class
In what instances you will declare a constructor to be private?
When we create a private constructor, we can not create object of the class directly from a client. So you
will use private constructors when you do not want instances of the class to be created by any external
client. Example UTILITY functions in project will have no 221 instance and be used with out creating
instance, as creating instances of the class would be waste of memory.
Can we have different access modifiers on get/set methods of a property?
No we can not have different modifiers same property. The access modifier on a property applies to both
its get and set accessors.
we write a goto or a return statement in try and catch block will the finally block execute?
The code in then finally always run even if there are statements like goto or a return statements.
What is Indexer?
An indexer is a member that enables an object to be indexed in the same way as an array.
Can we have static indexer in C#?
No
In a program there are multiple catch blocks so can it happen that two catch blocks are executed?
No, once the proper catch section is executed the control goes finally to block. So there will not be any
scenarios in which multiple catch blocks will be executed.

What is the difference between System.String and System.StringBuilder classes?
System.String is immutable; System.StringBuilder can have mutable string where a variety of operations
can be performed.


Access Specifiers 




In C#, the new keyword can be used as an operator, a modifier, or a constraint.
new Operator
Used to create objects and invoke constructors.
new Modifier
Used to hide an inherited member from a base class member.
new Constraint
Used to restrict types that might be used as arguments for a type parameter in a generic declaration.



The sealed modifier can be applied to classes, instance methods and properties. A sealed class cannot be inherited. A sealed method overrides a method in a base class, but itself cannot be overridden further in any derived class. When applied to a method or property, the sealed modifier must always be used with override (C# Reference).
Use the sealed modifier in a class declaration to prevent inheritance of the class, as in this example:
      sealed class SealedClass 
{
    public int x; 
    public int y;
}

// cs_sealed_keyword.cs
using System;
sealed class SealedClass
{
    public int x;
    public int y;
}

class MainClass
{
    static void Main()
    {
        SealedClass sc = new SealedClass();
        sc.x = 110;
        sc.y = 150;
        Console.WriteLine("x = {0}, y = {1}", sc.x, sc.y);
    }
}


The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.
In this example, the class Square must provide an implementation of Area because it derives from ShapesClass:
      abstract class ShapesClass
{
    abstract public int Area();
}
class Square : ShapesClass
{
    int x, y;
    // Not providing an Area method results
    // in a compile-time error.
    public override int Area()
    {
        return x * y;
    }
}


Abstract classes have the following features:
  • An abstract class cannot be instantiated.
  • An abstract class may contain abstract methods and accessors.
  • It is not possible to modify an abstract class with the sealed (C# Reference) modifier, which means that the class cannot be inherited.
  • A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.
Abstract methods have the following features:
  • An abstract method is implicitly a virtual method.
  • Abstract method declarations are only permitted in abstract classes.
  • Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature. For example:
    public abstract void MyMethod();
    
  • The implementation is provided by an overriding methodoverride (C# Reference), which is a member of a non-abstract class.
  • It is an error to use the static or virtual modifiers in an abstract method declaration.
Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.
  • It is an error to use the abstract modifier on a static property.
  • An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
An abstract class must provide implementation for all interface members.


The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly, as in this example:

The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members, as in this 
The protected keyword is a member access modifier. A protected member is accessible within its class and by derived classes. For a comparison of protected with the other access modifiers, see Accessibility Levels.
protected
A protected member is accessible within its class and by derived classes.
internal
Internal types or members are accessible only within files in the same assembly.
protected internal
Access is limited to the current assembly or types derived from the containing class.
* protected internal is the only access modifiers combination allowed for a member or a type.
So, as we can see “protected internal” can be used in the same assembly or types derived from the containing class in any assembly.
It means that we can access a “protected internal” method by accessing any instance of it’s class in the same assembly, in any class in different assembly which derives from the class, but we won’t be able to access the method by accessing an instance of it’s class in different assembly.
  1. // Assemby : A  
  2. namespace AssemblyA  
  3. {  
  4.     public class A  
  5.     {  
  6.         protected internal string SomeProtectedInternalMethod() {  
  7.             return "SomeValue";  
  8.         }  
  9.     }  
  10.   
  11.     public class A2 : A  
  12.     {  
  13.         public string SomeMethod() {  
  14.             // We can access the method because  
  15.             // it's protected and inherited by A2  
  16.             return SomeProtectedInternalMethod();  
  17.         }  
  18.     }  
  19.   
  20.     class A3 : A  
  21.     {  
  22.         public string SomeMethod()  
  23.         {  
  24.             A AI = new A();  
  25.             // We can access the method through an instance  
  26.             // of the class because it's internal  
  27.             return AI.SomeProtectedInternalMethod();  
  28.         }  
  29.     }  
  30. }  
  1. // Assemby : B  
  2. using AssemblyA;  
  3. namespace AssemblyB  
  4. {  
  5.     class B : A  
  6.     {  
  7.         public string SomeMethod() {  
  8.             // We can access the method because  
  9.             // it's inherited by A2  
  10.             // despite the different assembly  
  11.             return SomeProtectedInternalMethod();  
  12.         }  
  13.     }  
  14.   
  15.     class B2  
  16.     {  
  17.         public string SomeMethod()  
  18.         {  
  19.             A AI = new A();  
  20.             // We can't access the method  
  21.             // through the class instance  
  22.             // because it's different assembly  
  23.             return AI.SomeProtectedInternalMethod();  
  24.         }  
  25.     }  

MONDAY, NOVEMBER 19, 2012

OOPS

OOPS:


Abstract class:

    A class that serves only as a base class from which classes are derived. No objects of an abstract base class are created.
Ex:vb.net
Public mustinherit class person
{
//implementation
}
C#.net
Abstract class person
{
//implementation
}

For these classes we can’t create an object directly. We are declare one derived class and to inherit the base class. Then only we create an object to derived class.

Inheritance:

A relationship between classes such that some of the members declared in one class (base class) are also representing in the second class (derived class). The derived class inherits the members from the base class.

Multiple inheritance:

Multiple inheritance is a derived class declared to inherit properties of two or more parent classes.

Ex: vb.net:

Public class c1
 Public function hai() as string
    Msgbox(hi)
End class
Public class C2 inherits C1
    Msgbox(bye)
End class
Main()
Dim obj as new C2
C2.hai()
o/p: hi

C#.net:

Class C1
{
    Public string hai();
    MessageBox show(“hi”);
}
Class C2:C1
{
    Void Bye()
{
        MessageBox.show(“bye”);
}
}
Main()
{
    C2 obj=new C2;
    Obj.hai();
    Obj.Bye();
}

o/p: hi, Bye

Interface:

An interface can be defined as selection of subprogram without functionality.

Syntax: by default it is public
Vb.net:

Public interface <name>
    Sub setname(ename as string)
    Function Getname() as string
End interface
Public class emp implements person
    Dim name as string
Sub Setname(ename as string) implements person.setname
    Name=personname
End sub
Function getname() as string
End function return getname

C#.net:

Public interface <name>
{
    Void hello()
}
Class emp:person
{
    Void hello()
    {
        Messagebox.show(“hello”);
    }
}
End class

Note: you can’t create an instance of interface

Overridable:

    To indicate that a method may be overridden.





Ex: vb.net

Class C1
Public overridable subXX(0
Msgbox(“welcome”)
End class

Class C2
Public overrides subXX()
    Msgbox(“Bye”)
End class

Obj.XX()-> Bye->o/p

C#.net

Class C1{
    Public virtual string XX()
    {
        Msgbox.show(“welcome”);
    }
}
Class C2:C1
{
    Public override string XX()
    {
        Msgbox.show(“Bye”);
    }
}
Obj C2=new C2;
Obj.XX -> o/p=Bye


Must override:

To indicate that derived classes must provide their own implementation of a method using must override creates pure virtual also called abstract methods. These methods may not be used directly, but must be overriden.

Ex: vb.net

Public mustoverride subXX()
    Msgbox(“bye”)
End sub

C#.net:

Public abstract string XX()
        Msgbox.show(“bye”)

Not overriden:
To indicate that a method may not be overriden.

Vb.net:
Public Notoverridable subxx()
    Msgbox(“hai”)
End sub
Must inherits:

The class which doesn’t support instance creation is called must inherit class. In C++, Java it is called abstract class.
Ex: vb.net

Must inherits class C1
Public mustoverridable subxx()

End class

Class C2 inherits C1
Public overrides subxx()


  • Class: Logical representation of data.
  • Object: Physical representation of data.
  • Constructor: A special member function for automatically creating an instance of a class.
  • Destructor: A function that is called to deallocate memory of the object of a class.

Not inheritable:
The class which doesn’t support inheritance is called sealed class.
Ex: vb.net
Not inherits class C1
C#.net
Sealed class C1
Mybase:
To access methods in a base class when overriding methods in a derived class.

Me:
Me keywords provides us with a reference to our current object instance.
Myclass:
To call an overridable method in your class while making sure that implementation of the method in your class is called instead of an overridden version of the method.

Shadows:
The shadows keyword allows us to replace methods on the base class that the base class designer didn’t intend to be replaced.

Ex:
Vb.net:
Public shadows Readonly property  xx()Intiger
   Get
        Return 3.8
    End get
 End property
End class

Shared:

Shared data -> Shared Method -> Shared Constructor

Shared data:  when the data is attached to the class then it is called as shared data. This data will have only one memory instance which will be common to all the objects of the class.

Ex: public shared eno as byte

Shared method:   the method which is attached to the class is called as shared method. This method can access only by shared data.
Ex: public shared function XX() as byte

C#.net-> public static int xx()

Early binding:  Early binding means that our code directly interacts with the object by directly calling its method.(compilation time)

Late binding:   Late binding means that our code interacts with an object dynamically at runtime.

Access Modifiers:  

  1. Public : Entities declared Public have public access.There is no restrictions on the accessibility of the public entities.
  2. Private : Entities declared private have private access. They are accessible from their declaration context.

  1. Protected : Entities declared Protected have protected access. They are accessible only from within their own class or from a derived class. It is not a superset of friend class. You can use protected only at class level.

  1. Protected Friend: (protected internal) Entities declared in the protected friend have both protected and friend access. They can be used by code in the same class or as well as in derived class. The rules for protected and friend apply to protected friend as well.

  1. Friend: A function that has access to the private members of a class but is not itself a member of the class. An entire class can be a friend of another class.

Encapsulation: The mechanism by which the data and funtions ( manipulatiing this data) are bound together within an object definition.

Boxing: when we are converting value type as a reference type on the heap memory then it is called Boxing.

Ex: int a=20; Object b=a;It work implicitly.

Unboxing: when we are converting reference type to value type then it is called Unboxing. This will maintain on overhead towards the application. This will decrease the performance of application.

Ex: object a=20: int b=a;  Int b=int(a) -> implicit

Meta data: the collected information that describes an application is called metadata.

Name space: Name space is nothing but logical container for collection of classes.

  • Name space helps organize object libraries and hierarchies.
  • Simplify object references, prevent ambiguity when reffering to objects, and control the scope of object identifiers.

System collections: The collections name space is a part of the system name space and provides a series of classed that implement advanced array features.

  1. Array list: implements an array whose size increases automatically as elements are added.
  2. Bit array: Manages an array of Boolean that are stored as bits.
  3. Hash table:  Implements a collection of values organized by key. Sorting is done.

  1. Queue: Implements first in first out (fifo)

  1. Sorted list: Implements a collection of values with associated keys. The values are stored by key, and accessible by key or index.
  2. Stack: implements Last in First out(lifO)

System diagnostics: this name space provides classes that allow you to interact with system process, event logs and performance counters.

Deploymet: It is the process of taking an application and installing it on another machine.

Cabproject -> mergemodule project(.msm) -> setup project -> websetup project

Delegate:  a delegate is a class which acts as a function pointer.

    Features:

  1. It is provided with object-Oriented approach
  2. It refers to method of the object.
  3. A delegate is useful when you want to send one subprogram as a parameter to another subprogram.

Syntax: public Deligate sub XX()


Multicast deligate: it is a delegate that points to and eventually fires off several methods.

Thread: A thread can be defined as a unit of code having it’s own executing part.

  • Single thread: when the application is having only one process then it is called as single thread application.

  • Multi thread: when the application is having more than one process then it is called as multi thread application.
Methods: start(), shared sleep, suspend, resume, abort, join.

Asyschronus connection: ADO.net provides an option for asynchronous connection this can be achieved by multi threading.

Synchronization of threads:  Synchronization of the thread is allowing only one thread to work with block of statements. This can be achieved by applying the lock for set of statements.
Keyword:  synclock(“L1”)

Thread prorites: Above normal, normal, below normal, minimum.

No comments:

Post a Comment