Notes
IT Notes → C# @ December 22, 2020
- 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.
Subscribe
Login
0 Comments
Oldest