Notes
- Public – The type or member can be accessed by any other code in the same assembly or another assembly that references it. Private – The type or member can be accessed only by code in the same class or struct. Protected – The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class. Internal – The type or member can be accessed by any code in the same assembly, but not from another assembly. Protected internal – The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.
- The classes are internal by default whereas its members are private.
- Interfaces can contain methods, properties, events, indexers, or any combination of those four member types. Interface members are automatically public, and they can’t include any access modifiers. Members also can’t be static.
- A sealed class cannot be inherited.
- The constructor is provided by default if no other constructor is created by programmer.
- Any abstract method does not point to any method implementation.
- The variables that have type BaseClass continue to access the members of BaseClass, and the variable that has type DerivedClass continues to access members in DerivedClass first, and then to consider members inherited from BaseClass. The keyword new, you are asserting that you are aware that the member that it modifies hides a member that is inherited from the base class and hence no compiler warning. This is known as shadowing. When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member. You cannot use the virtual modifier with the static, abstract, private, or override modifiers. Methods override using override keyword.
- The main method is static void Main(string [] args)
- Abstract class and methods can be provided and a class has to be abstract if abstract method is provided
- Extension methods extend the default methods provided to say data type like int where we use static class and methods and provide this in parameters
- There is positional and named arguments wherein named argument is written as below and can be provided only after positional arguments
- Example is
show (name:”vinod”, age:”29”, “chess, cricket”);
- Indexers can be provided for a class as below
-
Class IPAddress { public int ip[]; public int this [int index] { get { return ip[index]; } set { ip[index] = value; } } } IPAddress myip= new IPAddress(); myip[0] = 0;
- Reference variables use ref in calling arguments as well as called parameters.
- It is used in generics and function call is swap(ref a, ref b)
- Narrowing can occur with int as well as float and for integers it is called truncation and for floats it results in PositiveInfinity for overflow and NegativeInfinity for underflow. We can check by IsInfinity.
- If P p1 = new P() and E p2 = new E() where P and E represent person and employee e1 = (E) p1 may result in ClassCastException.
- Arrays can be casted as with its individual types. Otherwise ArrayMismatchException occurs.
- For incompatible conversions we use (1) (int.Parse etc) parsing that can result in FomatException occurs (2) System.Convert (3) Sytem.BitConveter.
- Unmanaged code is that code written outside CLR which is Common Language Runtime. They are ActiveX and Win32 code. They can be utilized using P/Invoke and COM Interop.
- P/Invoke uses DLLImport(“kernel32.dll”, CharacterSet = Character.Auto, SetLastError=true) which are the DllName, Charcter Set and entry point inside DLL which would be method called if not provided. This can be used along with MarshallAs as in following
Static extern uint GetShortPathName ([MarshallAs(UnManagedType.LPSTR)] string Pathname);
- For COM Interop we use Add Reference from Solution Explorer and gets information on members and uses dynamic (Static data type) for variables whose data types need to checked only at runtime. This can be done implicitly as you don’t declare or explicitly.Strings that store same value points to same entry in intern pool and hence have been kept immutable.
- Some of the string constructors take (1) array of characters, (2) array of characters along with start and count and (3) character with repeat count.
- String indexers are read only.
- Compare (a,b) gives 1 if a.
- StringBuilders are mutable with no indexers and are faster for 7 or more concatenations.
- StringWriter used for only concatenations are when a class derived from TypeWriter is required. StringReader when a class derived from TypeReader required.
- Strings can be formatted by ToString and String.Format.
- Standard format strings are C c (currency $), D d (decimal), E e (scientific), F f (fixed-point), G g (general-comma and decimal), N n (numeric), P p (percent), X x (hexadecimal). There are also Custom format strings.
- For dates we have d D, f F (Full) and g G (General) with small letter indicating shorter form.
- Constructors are called as A (int a) : base(a) or : this(a).
- If a class implements Interface explicitly, we need to use interface members through instance of interface. Here the Interface name is used along with relevant method implementation inside class. With explicit interface implementations you can only access them when class object assigned to the interface instance. Class object can’t otherwise access interface methods.
- With implicit interface implementation you access the interface methods and properties as if they were part of the class. With implicit interface implementation you access the interface methods and properties as if they were part of the class.
- If a class inherits from 2 or more interfaces and if the interfaces happen to have the same method names, the class doesn’t know which interface method is being implemented if you use implicit interface implementation? This is one of the scenarios when you would explicitly implement an interface.
- IComparable has int CompareTo(Class ClassObject) and its generic form used in Array.Sort(ClasObject).
- IComparer has int Compare(Class ClassObject) and its generic form used in Array.Sort(ClassObject, SortBy).
- IEquitable has bool Equals(Class ClassObject) used in ClassObject.Contains(ClassObject).
- ICloneable has Object Clone() used in Object.Clone(). It uses shallow cloning if second parameter is false and deep cloning if true.
- IEnumerable has IEnumerator GetEnumerator and its generic form.
- IEnumerator has int Current property and bool MoveNext(), void Reset(), void Dispose().
- You can also use Yield which returns IEnumerable.
- GarbageCollector GC has a non-deterministic finalization where it calls Finalize method.
- Destructors are created with ~and class name and cannot be called directly. They are converted to Finalize method by compiler and we can’t override Finalize method. The unmanaged resources are cleared by Destructors.
- IDisposable has Dispose method that clears managed resources and can also clear unmanaged resources.
- If dispose is called, we won’t call destructors as managed resources may be attempted to free twice. Also, we call GC.Finalization to stop Finalize call being invoked once Dispose is called.
- Using is a keyword we can used to ensure unmanaged code is freed in the end.
- They have following forms.
-
using (DisposableClass object = new DisposableClass) {} DisposableClass object = new DisposableClass; using(object) { } DisposableClass object; using (object = new DisposableClass) {}
- Delgates are function delegates or callbacks which are completed once function completes execution
- public delegate type delegatemethod(parameters);
- public delegatemethod = method;
- Covariance means return type can be a subclass whereas contravariance means parameter can be superclass for the method
- Action delegate returns void whereas function delegate returns a value
-
Public Action< T1> (T1 arg) // Public delegate void delegatename(T1 arg); delegatename = methodname; Public Func(T1, TResult> (T1 arg) // Public delegate TResult delegatename(T1 arg); delegatename = methodname;
- Anonymous methods use delegate([parameters]) {code} which is like () => expression; or even param => expression for one parameter.
- Asynchronous works like await DoSomethingAsync(); and async task DoSomethingAsync();.
- Events have a single publisher and many subscribers.
- public event EventHandler Eventname;.
- Events passes two parameters which are the object which raises the event and the parameters derived from EventArgs class that passes arguments to the events.
- If we subscribe more than once the event handler is called that many times. If we unsubscribe when not subscribed it creates no error.
- In event delegete a delegate is declared with event.
- Try catch is used for exception handling. The base exception is Exception and we can create our exception by inheriting from exception and creating methods with parameters overridden to base constructors.
- If a method gives information on exception through return value throwing of exception can be ignored.
- [Serializable] to ensure exception crosses AppDomain boundary.
- Debug.Asset halts execution if false.
- Thow new Exception (Data, HelpLink,HResult, Message, Source,StackTrace, TargetSite) Here exception stack is reset to current location Simple throw would keep the stack.
- We can make class derive from Exception with each method call to base with information and no code.
Delegate
- It is similar to function pointer and is type safe.
- It dynamically wires up a method caller to its target method.
- It helps in writing plug-in methods.
- A delegate can have more specific parameter types than its method target. This is called contravariance.
- The return type of a delegate can be less specific than the return type of its target method. This is called covariance.
- Func and Action delegates.
- Internally System.Delegate acts as base for System.MulticastDelegate which has target (class = null for static) and method which holds instance of MethodInfo class for the method.
- Anonymous delegate:
delegate del = delegate(params){};
Generics
- Reusability with a “template” that contains “placeholder” types.
- Generic types are not covariant. This means that even if B can be cast to A, T<B> cannot be cast to T<A>.
- Three kinds of constraints are derivation constraint, constructor constraint and reference/value constraint.
- In derivation constraint base constrained must never have lower visibility than generic type parameter.
- Order: (1) reference/value constraint (2) derivation constraint (3) constructor constraint.
Indexers
public string this [int arg1, string arg2] { get { ... } set { ... } }
LINQ
- Structured type-safe queries over local object collections (any collection implementing IEnumerable<>,) and remote data sources.
- Uses Enumerable class and Queryable class.
- Sequences and elements.
- Take, Skip, and Reverse.
- FirstOrDefault, LastOrDefault, SingleOrDefault, or ElementAtOrDefault.
- Aggregation operators: Count, Min, Max, and Average.
- Contains, Any, All, and SequenceEquals.
- Concat, Union, Intersect, Except.
- Deferred or lazy evaluation.
- Lazy execution defeated by element operators, aggregation operators, and quantifiers and also conversion operators: ToArray, ToList, ToDictionary, ToLookup.
- Chaining query operators.
- Query syntax or query comprehension syntax gives advantage of (1) let clauses for introducing new variables (2) Multiple generators (SelectMany) or Join or GroupJoin equivalent followed by an outer iteration variable reference.
- Following into clause, the previous iteration variable is out of scope.
- Cast, OfType.
Interface
- Class can implement multiple interfaces.
- Interfaces are abstract.
- It can be defined as a contract.
C# 4.0
Newly introduced features are
- Dynamic lookup.
- Named and optional arguments.
- Variance
Boxing and Unboxing
- Boxing is the act of casting a value type instance to a reference type instance.
- Unboxing reverses the operation, by casting the object back to the original value type and requires explicit conversion.
Performance For Generics
- When we use object instead of generic variable for value types, we waste on boxing effort and for both value and reference we waste at the point of down casting to individual type.
- Also type safety at the time of down casting is not considered.
- Server compiler compiles it into IL where there is placeholder for types and meta information regarding them.
- For value types client compiler converts IL to machine code where value is replaced and for reference replace it with objects. Code reuse not object reuse is done wherever possible.
- You can expect around 200% performance gain on value types and 100% on reference types.
Classes
- Partial Classes and Methods.
- Automatic Properties.
- Reference to a base class can refer to an instance of a subclass.
- An upcast operation creates a base class reference from a subclass reference.
- A downcast operation creates a subclass reference from a base class reference. It has to be explicit.
- The as operator performs a downcast that evaluates to null if the downcast fails.
- The is operator tests whether a downcast would succeed.
- Any abstract member forces the entire class to be abstract. So, no actual object instances of base class. It has empty implementation.
- A function marked as virtual can be overridden by subclasses wanting to provide a specialized implementation.
- Remember override and base.
- From subclass to base class constructor arguments are evaluated and in reverse order constructor bodies execute.
- In case of method overloading, when an overload is called, the most specific type has precedence. The particular overload to call is determined statically (at compile time) rather than dynamically (at runtime).
- Accessibility internal by default for non-nested classes.
- A subclass itself can be less accessible than a base class, but not more accessible.