0% found this document useful (0 votes)
34 views68 pages

Web D and .Net Notes Section-A Part-2

Uploaded by

abmcs23009diksha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
34 views68 pages

Web D and .Net Notes Section-A Part-2

Uploaded by

abmcs23009diksha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 68
Properties in C#.Net (smart accessors/mutator (getter and setter): a new member) Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written or manipulated. Properties do not name the storage locations. Instead, they have accessors that read, write, or compute their values. For example, let us have a class named Student, with private fields for age, name, and code. We cannot directly access these fields from outside the class scope, but we can have properties for accessing these private fields. Note: These are a smart solution to replace accessor and mutator methods of a class in OOP language. Accessors: The accessor of a property contains the executable statements that helps in getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both. For example: W Declare a Code property of type string: public string Code { c retum code; set { code = value; } } 1 Declare a Name property of type string: public string Name { Bet { retum name; i set name = value; } } M Declare a Age property of type int: public int Age { get { return age; 43‘Property name and deta member names must not be same. In above example Cade and code ae two diferent variables. 2) get, set and value ae keywords. Example: using System; System.Collections.Generic; using System.Ling; using System. Text; namespace ConsoleApplication2 { class Student { private double m; public double Marks { get { return m; } set { m= value; } ) } class Program { static void Main() { Student t = new Student(); t.Marks = 459; System.Console.WriteLine("Student marks are: " + t.Marks); System.Console.ReadLine(); } } }‘Same program without using properties (i.e. using accessor and mutator methods)/ Traditional without Properties: using System; namespace ConsoleApplication2 Sas Sudent ‘ private double m; public void InputMarks(int x) ; m=x; } public double OutputMarks() { return m; i class Program { static void Main() { ‘Student t = new Student(); tInputMarks(459); System.Console. WriteLine("Student marks are: " + t,OutputMarks()); System.Console.ReadLine(); } } } ‘Types or categories of properties in C#.net: 1) Read-write property. 2) Read-only property. 3) Write-only property 4) Auto-implemented property. 1)Read-write property means properties having both get and set blocks. 2)Read-only property means properties having only get block. eg. class Student { private double m=99; public double Marks 1 m= value; ny } } class Program { static void Main(){ Student t= new Student(); I-Marks = 459; System.Console, WriteLine("Student marks are: System.Console.ReadLine(); } } 3)Write-only property; properties having only set block. clas Student { Private double m; mete double Marks. Mget mK return m; n set { m= value; } } } class Program static void Main() ‘Student t = new Student(); t-Marks = 459; System.Console. WriteLine("Student marks are: * + Marks); System.Console.ReadLine(); } } 4) Auto implemented property The patterns you see here, where a property encapsulates a property withget and set accessors, without any other logic is common. It is more code than we should have to write for such a common scenario. That’s why C# 3.0 introduced a new syntax for a property, called anauto-implemented property, which allows you to create properties without ger and ser accessor implementations. These may be further classified as read-write auto implemented, read-only auto implemented, write-only auto implemented properties. Below example shows how to add auto-implemented properties to a class. using System; ; using System Collections. Generic; using System.Ling; using System. Text; namespace ConsoleApplication? class Student { public double Marks Bet; set; 46} } class Program { static void Main() ‘Student t= new Student(); t-Marks = 459; ‘System.Console. WriteLine("Student marks are: "+ ‘t.Marks); ‘System.Console.ReadLine(); } } } Notice how the get and set accessors in above example do not have implementations. In an auto-implemented property, the C# compiler creates the backing store field behind the scenes, giving the same logic that exists with traditional properties, but saving you from having to use all of the syntax of the traditional Property. As you can see in the Main method, the usage of an auto-implemented property is exactly the same as traditional properties, which you learned about in previous sections.Arrays in C#.Net An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contiguous memory locations. Declaring Arrays To declare an array in C#, you can use the following syntax: datatype[] arrayName; where, * datatype is used to specify the type of elements in the array. * [J specifies the rank of the array. The rank specifies the size of the array. * arrayName specifies the name of the array. For example, double[] balance; Initializing an Array Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array. Array is a reference type, so you need to use the new keyword to create an instance of the array. For example, double{] balance =new double[10]; Assigning Values to an Array ‘You can assign values to individual array elements, by using the index number, like: double{] balance =newdouble[10]; balance{0}=4500. ‘You can assign values to the array at the time of declaration, as shown: double[] balance ={2340.0,4523.69,3421.0}; ‘You can also create and initialize an array, as shown: int{] marks =newint[5]{99,98,92,97,95}; You may also omit the size of the array, as shown: int{] marks =newint{] {99,98,92,97,95}; You can copy an array variable into another target array variable. In such case, both the target and source point to the same memory location: int{} marks =newint{] {99,98,92,97,95}; int{] score = marks; When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0. Accessing Array Elements 48An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example, double salary = balance[9]; The following example, demonstrates the above-mentioned concepts declaration, assignment, and accessing arrays: usingSystem; namespaceArrayApplication { classMyArray { staticvoidMain(string[] args) int{]_n =new int{10];/* n is an array of 10 integers */ int ij; /* initialize elements of array n */ for i =0; i (T[] array, int index) { if (index Microsoft Corporation. All rights reserved.Nested class example(Containment example): class c2, { public class c3 { public int x=10; public void £234() { x=200; } } (factory method public ¢3 f123() { 3 ob3=new c3(); return 0b3; } } class cl { public static void Main(string [Jargs) { 2 ob=new c2(); ob.f123().f234(); System.Console. WriteLine(ob.f123().x); Microsoft ras Visual C# 2418 Compiler version 4.6.30319.1 Copyright (C) Microsoft Corporation. All rights reserved. 1 EROT-5 18 ER Note: A class containing an object of other class is also containment.Abstract class Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy, An Abstract class is an incomplete class or special class we can't instantiate, We can use an Abstract class as a Base Class. An Abstract method must be implemented in the non-Abstract class using the override keyword. After overriding the abstract method is in the non-Abstract class. We can derive this class in another class and again we can override the same abstract method with it. Features: 1 2. SPA NAHwAY An abstract class can inherit from a class and one or more interfaces. An abstract class can implement code with non-Abstract methods (means 0-100% abstraction). . An Abstract class can have modifiers for methods, properties etc. . An Abstract class can have constants and fields. . An abstract class can implement a property. . An abstract class can have constructors or destructors. . An abstract class cannot be inherited from by structures. . An abstract class cannot support multiple inheritance. Example 1: #region //An abstract calss can inherit from a class and one or more interfaces. interface [VendorTransDetails { } void getVendorID(); interface IClaimsTracker { void getSeqID(); } class ClaimsMaster { string getDCNNO() { return "PC20100308A 00005"; Example 2: 96abstract class Abstract : ClaimsMaster, IClaimsTracker, IVendorTransDetails { (Mere we should implement modifiers oterwise it throws complie-time error public void getVendorl10() { int s = new int(); s= 001; Console. Write(s); } public void getSeqID() { int SeqID = new int(): SeqID = 001; Console. Write(SeqID): } } #endregion Example 3: #region //An abstract class can implement code with non-Abstract methods. abstract class NonAbstractMethod /Mt is a Non-abstract method we should implement code into the non-abstract method on the class. public string getDen() { return "PS20100301A0012"; } public abstract void getSeqID(); } class Utilize : NonAbstractMethod { public override void getSeqID() { } } #endregion Example 4: #region //Abstract class can have modifiers for methods,properties and An abstract class can implement a property ; public abstract class abstractModifier rrivate int id; , 7public int ID { get { return id; } set {id= value; } internal abstract void Add(); : #endregion Example 5: #region Abstract class can have constant and fields public abstract class ConstantFields { public int no; private const int id = 10; } #endregion Example 6: #region //An abstract class can have constructors or destructors abstract class ConsDes { ConsDes() { , ~ConsDes() ‘ 2 } #endregion Example 7: #region //An abstract class cannot be inherited from by structures public struct test { //Ne can't inheritance the struct class on the abstract class abstract class NotInheritanceStruct { } #endregion Example 8: #region a //An abstract class cannot support multiple inheritance class A { 98} class B: A { abstract class Container : B //But we can't iherit like this : A,B { egal Abstract class vs. Interface An abstract class can have abstract members as well as non abstract members (i.e. 0 to 100% abstraction). But in an interface all the members are implicitly abstract (i.e. always 100% abstraction) and all the members of the interface must override to its derived class. An example of interface: interface iSampleInterface MAlI methods are automaticall abstract int AddNumbers(int Num 1, int Num2); int MultiplyNumbers(int Num1, int Num2); } Defining an abstract class with abstract members has the same effect to defining an interface. The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.A class can inherit one or more interfaces, but only one abstract class. Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes. The selection of interface or abstract class depends on the need and design of your Project. You can make an abstract class, interface or combination of both depending on your needs.Polymorphism Polymorphism means to exists in more than one form and is derived from term “Polymorphic” where Poly (means many)+ morphic (means form). i.e same task perform more than one actions is known as polymorphism. For example: to condense the customer differently, to draw something ¢.g. shape or rectangle etc. Other example of abs() function i.e. if a language supports overloading then this provides a common abs() function to find absolute value for integer, float, double etc else different- different functions. Same is a case of user-defined functions means you can serve clients with common function name over different parameters/signatures, We use method overloading and method overriding to achieve polymorphism. Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc. Technical examples (benefits of polymorphism): sqrt) function can perform square root of integer, float, double etc if language supports overloadi € user has to remember only one name of function. ob.f123(); statement can call different f123 functions of different sub classes (depends on object ‘ob’ contained address of which sub class) if language supports overriding. Types: Polymorphism is of two types 1)Compile time/Early-time/Static e.g. Overloading-Method overloading, Constructor overloading, Operator overloading(not supported by Java even few operators are provided in- built overloaded and others are not provided due to JVM complexities but supported by C#.net). 2) Run-time/Late-time/ Dynamic e.g. Method overriding (overriding is possible because of inheritance i.e. same signature of function even returning type in super and sub class). Method overloading examples: egl class cl { public void £1230) { System,Console. WriteLine("'without arguments"); } public void f123(int x) { System.Console.WriteLine(x); } public void £123(int x, int y) { ’ i System.Console. WriteLine("Values are: " +x +); // check if only x+y is printed} } class abe public static void Main(string{] args) el ob=new cl(); , ob.f123(); / invokes first 123 function ob.f123(5); // invokes second £123 function ob.f123(5, 6); // invokes third £123 function ‘System.Console.ReadLine(); } } } Operator overloading examples: egl class cl 100{ int x; int y5 public c1(){} public cl(int p, int q) { =P ia public void disp() ft System.Console. WriteLine(x+" and "+y); } public static ¢1 operator+(cl obl,cl ob2) { ol obt=new cl(); obt.x=0b1.x+0b2.x; obty=ob1.ytob2.y; retum obt; } } class abe { Public static void Main(String{} args) { 1 obj =new c1(10,20); 1 obj2=new c1(100,200); obj | disp(); obj2.disp0; el obj3-new c1(); (0bj3=0bj +0bj2; 0bj3.disp0; System.Console.ReadLine(); . } Method Overriding (virtual and override keyword) In C#, for overriding the base class method in derived class, you have to declare base class method as virtual and derived class method as override as shown below:(new Keyword Vs virtual and override keywords(method hiding Vs overriding)) As you know Polymorphism is the concepts of OOPS which includes method overriding and method overloading. virtual and override keywords are used for method overriding and new keyword is used for method hiding. using System; namespace Polymorphism { class A { 101public virtual void Test() { Console. Writel ine("A::Test()"), } i B:A ee override void Test() { Console, Writel ine("B::Test()"); } cas C:8 a override void Test() { Console. WriteLine("C::Test()"); } Law Program { static void Main(string[] args) Ce=newC(); a.Test(); // output --> "A::Test()" b.Test(); // output --> "B::Test()" c.Test(); // output --> "C::Test()" a=new Bi); a.Test(); // output --> "B::Test()" // bez overriding means compiler must ignore the type object but must consider only the point /fhat object contains the reference of which class. So, Test() of B is invoked. Reverse result is Healled method hiding not overriding. b=new C(); b.Test(); // output --> "C::Test()" Console.ReadKey(); } } } Note: : : i) Advantage of method overriding by using downcasting is that we can do different tasks by single statement like ob.1123(); Where, ob is an object of super class down-casted to several different stb-classes. cl obfJ=new cl [10]; ob[0]=new ¢2(); ob{1]=new ¢3(); ob[2}=new c4(); ob{3]-new c5(); 102Hlete for(int i=0;i "A::Test()" b.Test(); // output --> "B::Test()" c.Test(); // output -> "C::Test()" a=new BO); 103a.Test(); // output —> "A::Test()" b=new CQ; b.TestQ); // output --> "B::Test()" Console.ReadKey(); } } } When you will run the above program (method hiding) without use of new keyword, it will run successfully and gives the O/P (by default C# compiler thinks of hiding). But this program will show the two warnings as shown below: 1. ‘Polymorphism.B.Test()' hides inherited member 'Polymorphism.A.Test()'. Use the new keyword if hiding was intended. 2. 'Polymorphism.C.Test()' hides inherited member 'Polymorphism.B.Test()'. Use the new keyword if hiding was intended. Note:In Java method hiding was achieved by static methods but here in C# we cannot mark static methods as virtual or override because static members cannot be accessed with object i.e only with class name (but in Java it is possible to access static elements with class and with object as well). So, to achieve the same (hiding concept) an extra keyword “new” is introduced. Mixing Method Overriding and Method Hiding You can also mix the method hiding and method overriding by using virtual and new keyword since the method of a derived class can be virtual and new at the same time. This is required when you want to further override the derived class method into next level as | am overriding Class B, Test() method in Class C as shown below: using System; namespace Polymorphism { class A { public void Test() { Console. WriteLine("A::Test()"); } } class B: A { public new virtual void Test() { Console. WriteLine("B::Test()"); } } class C:B 104{ nai override void Test() { Console. WriteLine("C::Test()"); J class Program { static void Main(string[] args) { Aa=new AQ; Bb=new BQ; Cc=new C(); a.Test(); // output --> "A::Test()" b.Test(); // output --> "B::Test()" ¢.Test(); // output -> "C::Test()" a=new BQ); a.Test(); // output --> "A::Test()" b=new CO; b.Test(); // output --> Console.ReadKey(); est()" 1. The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allows it to be overridden in the derived class. 2. The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into derived class, The new keyword is used to hide a method, property, indexer, or event of base class into derived class. 3.sealed Keyword In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the NotInheritable keyword serves the purpose of sealed. In Java final keyword is used for same purpose. Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as a sealed class, the class cannot be inherited.If a class is derived from a sealed class then the compiler throws an error. If you have ever noticed, structs are sealed. You cannot derive a class from a struct. The following class definition defines a sealed class in C#: // Sealed class sealed class SealedClass { } In the following code, I create a sealed class SealedClass and use it from Class]. If you run this code then it will work fine. But if you try to derive a class from the SealedClass, you will get an error. using System; class Class1 { static void Main(string[] args) { SealedClass sealedCls = new SealedClass(); int total = sealedCls.Add(4, 5); Console. WriteLine("Total = " + total.ToString()); } } /! Sealed class sealed class SealedClass ' public int Add(int x, int y) { return x + y; } } Sealed Methods and Properties You can also use the sealed modifier on a method or a property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent other developers that are using your derived classes from overriding specific virtual methods and properties. class X{ protected virtual void F() { Console. WriteLine("X.F"); } protected virtual void F2() { Console, WriteLine("X.F2"); } class Y : X { sealed protected override void F() { Console. WriteLine("Y.F"); } protected override void F2() { Console. WriteLine("X.F3"); } } class Z: Y { // Attempting to override F causes compiler error CS0239. // protected override void F() { Console. WriteLine("C.F"); } // Overriding F2 is allowed. protected override void F2() { Console. WriteLine("Z.F2"); } } Note: We can use sealed keyword with methods that are overridden in derived class because in base class method without virtual keyword is non-overridable (i.e. sealed) by default. So, no any need of sealed keyword (even cannot use sealed keyword with methods not having override keyword) with methods of base classes. sealed is used only with methods that are overridden in derived classes and you want to exclude it from further override in next level inheritance ( methods with override keyword in derived are also inheritable in next level class). Why Sealed Classes? The vast majority of .NET programmers let their classes “unsealed” without even considering making them sealed. If a class was not designedly made inheritable, it is very probably even impossible to inherit from it and override members reasonably. On the other hand, overriding members of the class which were not designed to be overridden might cause unpredictable results. For example a class that implements security features, so that the original object cannot be "impersonated".readonly and const Keyword The readonly keyword is a modifier that you can be used on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class. The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants as in the following example: Example: In this example, the value of the field year cannot be changed in the method ChangeYear, even though it is assigned a value in the class constructor: class Age { readonly int _ year; Age(int year) { _year = year; } void ChangeYear() //_year = 1967; // Compile error if uncommented. } } You can assign a value to a readonly field only in the following contexts: + When the variable is initialized in the declaration, for example: * public readonly int y = 5; Other Example: public class ReadOnlyTest class SampleClass public int x; // Initialize a readonly field public readonly int y = 25; public readonly int z; public SampleClass() // Initialize a readonly instance field z= 24; } public SampleClass(int p!, int p2, int p3) { x=pl; 108static void Main() SampleClass p1 = new SampleClass(11, 21, 32); // OK Console.WriteLine("p1: x={0}, y={1}, 2=(2}", pl.x, pl ; . . » PLX, ply, pl.2); SampleClass p2 = new SampleClass(); p2.x=55; // OK Console. WriteLine("p2: x={0}, y={1}, 2={2)", p2.x, p2,y, p22); In the preceding example, if you use a statement like tl p2.y = 66; // Error You will get the compiler error message. In the preceding example, if you use a statement like this: public const int n; /finstead of below public const int n=99; “will give an error Error 1. A .const field requires a value to be provided More examples: Example 1: using System; using System.Collections.Generic; using System.Ling; using System.Text ; namespace ConsoleApplication10 classProgram it publicconstint x=10; publicreadonlyint y; public Program() Console.WriteLine("Enter y:\n"); y=Convert .ToInt32(Console .ReadLine ()); } staticvoid main(string[] args) { : Program ob=newProgram ()3 Console.wWriteLine(x); fe//cannot write like Console.WriteLine(ob.x)5 Console.wWriteLine(ob.y); //cannot write like Console.wWriteLine(y); Console.ReadLine(); } } Example 2: using System; using System.Collections.Generic; using System.Ling; using System.Text; namespace ConsoleApplication1e classProgram { staticvoid Main(string[] args) t constint x=10; readonlyint y=20; 7/ ERROR bcz readonly can be applied with data Console.WriteLine("Enter y:\n"); y=Convert .ToInt32(Console .ReadLine ())5 Console.WriteLine(x) ; Console.WriteLine(y); Console.ReadLine(); } members of a class

You might also like