Студопедия

Главная страница Случайная страница

Разделы сайта

АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторикаСоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника






Difference between value types and reference types.






There are twocategories of data type: Value types and Reference types.

Value type: stores its value directly. In memory stored in an area called stack.

Reference type: stores a reference to the value. In memory stores in an area called managed heap.

All numeric data types

· Boolean, Char, and Date

· All structures, even if their members are reference types

· Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong

Reference types include the following:

· String

· All arrays, even if their elements are value types

· Class types, such as Form

· Delegates

 

 

9. Conditional statements in C#.

Conditional statements allow you to branch your code depending on whether certain conditions are met or on the value of an expression. Conditional Statements are basic building blocks of program that controls the flow of a program. It executes a particular block of statement based on a Boolean condition, which is an expression returning true or false. These are statements are also known as Decision making statements. Therefore, conditional statements allow you to take logical decisions about executing different block of program to achieve the required logical output. C# supports various types of conditional Statements they are as follows.

if statement will evaluate the condition. If it is true, it will execute the statements that follow it. Otherwise, it will leave the block of statements that are followed by it.
Simple e.g. I will go to market if got time. So, here time is the constraints that will evaluated. If I have time this will be true then only will go to market.

If(condition){ //block of statements}

if else statement will evaluate the condition. If condition is true, it will execute the statements that follow if block.Otherwise, it will execute the statements that are followed by else block.
Simple e.g. I will go to market if got time else I will be at home. So, here time is the constraints that will evaluated first.If I got time then I will be at market else I will be at home.

If(condition){ //block of statements}

else(condition){ //block of statements}

Ternary Operator. The conditional operator behaves like a simple if…else statement.

Condition? Statement1: Statement 2

The compiler will first evaluate the condition. If the Condition is true, then it will execute statement 1, otherwise it will execute statement 2.

 

10. Loops in C#.

looping - the ability to repeat a block of code N times.

Do{} While{}. The loop’s test condition is evaluated after the body of the loop has been executed. The do loop evaluates the condition after the loop has executed, which makes sure that the code block is always executed at least once.

do{ Console.WriteLine(number); number = number +1; } while(number < 5);

The for loop is a bit different. It's preferred when you know how many iterations you want, either because you know the exact amount of iterations, or because you have a variable containing the amount.

for (initializer; condition; iterator)

statement(s)

where: The initializer is the expression evaluated before the first loop is executed (usually initializinga local variable as a loop counter).The condition is the expression checked before each new iteration of the loop (this must evaluate to true for another iteration to be performed). The iterator is an expression evaluated after each iteration (usually incrementing the loop counter).The iterations end when the condition evaluates to false.

The while loop Unlike the for loop, the while loop is most often used to repeat a statement or a block of statements for anumber of times that is not known before the loop begins. Like the for loop, while is a pretest loop. The syntax is similar, but while loops take only one expression:

while(condition)

statement(s);

The foreach loop allows you to iterate through each item in a collection. Syntax:

foreach (int temp in arrayOfInts) { Console.WriteLine(temp); }

Ex: foreach (int var in x){ var+=10; }

 

11. Jump statements in C#.

There are five types of jump statements used in C# as follows: Goto, Break, Continue, Return, Throw.

The goto statement allows you to jump directly to another specified line in the program, indicated by a label: goto Label1; Console.WriteLine(" This won't be executed"); Label1: Console.WriteLine(" Continuing execution from here");

A couple of restrictions are involved with goto. You can’t jump into a block of code such as a for loop, you can’t jump out of a class, and you can’t exit a finally block after try.catch blocks. The reputation of the goto statement probably precedes it, and in most circumstances, its use is sternly frowned upon. In general, it certainly doesn’t conform to good object-oriented programming practice. break statement —. Controlwill switch to the statement immediately after the end of the loop. If the statement occurs in a nested loop, control will switch to the end of the innermost loop. If the break occurs outside of a switch statement or a loop, a compile-time error will occur. The break will exit only a single loop iteration. The continue statement is similar to break, and must also be used within a for, foreach, while, or do...while loop. However, it exits only from the current iteration of the loop, meaning that execution will restart at the beginning of the next iteration of the loop, rather than outside the loop altogether. It is used to transfer the program control to the beginning of the loop. It continues until a specific condition is satisfied; in other words, the continue statement skips the remaining code in the loop and the pointer is sent to the beginning of the loop. The continue statement tells the complier to skip the following statements and continue with the next iteration. The return statement is used to exit a method of a class, returning control to the caller of the method. If the method has a return type, return must return a value of this type; otherwise if the method returns void, you should use return without an expression.

 

12. Enumerations in C#.

An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. For example, assume that you have to define a variable whose value will represent a day of the week. There are only seven meaningful values which that variable will ever store. To define those values, you can use an enumeration type, which is declared by using the enum keyword.

Creating an enumeration can save you a lot of time and headaches in the long run. At least three benefits exist to using enumerations instead of plain integers:

➤ As mentioned, enumerations make your code easier to maintain by helping to ensurethat your variables are assigned only legitimate, anticipated values.

➤ Enumerations make your code clearer by allowing you to refer to integer values by descriptive names rather than by obscure “magic” numbers.

➤ Enumerations make your code easier to type, too. When you go to assign a value to an instance of an enumerated type, the Visual Studio.NET IDE will, through IntelliSense, pop up a list box of acceptable values to save you some keystrokes and to remind you of what the possible options are.

You can define an enumeration as follows:

public enum TimeOfDay{

Morning = 0,

Afternoon = 1,

Evening = 2 }

 

13) Namespaces in C#.

The namespace keyword is used to declare a scope that contains a set of related objects. We can use a namespace to organize code elements and to create globally unique types.

Every time you make a new program, you define a namespace for it so that its code is separate from the.NET Framework classes

Namespace

Class

Method 1

statement

statement

Method 2

statement

statement

 

Namespaces let us use the same name in different programs, as long as those programs aren’t also in the same namespace.

A namespace has classes in it, and classes have methods. Inside each method is a set of statements.

 

14) Main() method in C#.

Every C# application must contain a single Main method specifying where program execution is to begin. In C#, Main is capitalized.

Main can only return int or void, and has an optional string array argument to represent command-line parameters:

C#

static int Main(string[] args)

{

//...

return 0;

}

The string array parameter that contains any command-line arguments passed in works just as in Java. Thus, args[0] specifies the first command-line parameter, args[1] denotes the second parameter, and so on. The args array does not contain the name of the EXE file.

15) Console input/output in C#.

When a console application starts, the operating system automatically associates three I/O streams with the console: standard input stream, standard output stream, and standard error output stream. To read a line of text from the console window, we use the Console.ReadLine() method. This will read

an input stream (terminated when the user presses the Return key) from the console window and return the input string. There are also two corresponding methods for writing to the console, which you have already used extensively:

➤ Console.Write() — Writes the specified value to the console window.

➤ Console.WriteLine() — This does the same, but adds a newline character at the end of the output.

Various forms (overloads) of these methods exist for all the predefined types (including object), so in most cases you don’t have to convert values to strings before we display them. For example, the following code lets the user input a line of text and displays that text:

string s = Console.ReadLine();

Console.WriteLine(s);

Console.WriteLine() also allows you to display formatted output in a way comparable to C’s printf() function. To use WriteLine() in this way, you pass in a number of parameters. The first is a string containing markers in curly braces where the subsequent parameters will be inserted into the text. Each marker contains a zero-based index for the number of the parameter in the following list. For example, {0} represents the first parameter in the list. Consider the following code:

int i = 10;

int j = 20;

Console.WriteLine(" {0} plus {1} equals {2}", i, j, i + j);

 

 

16) Comments in C#.

Comments can be used to document what the program does and what specific blocks or lines of code do. Since the C# compiler ignores comments, we can include them anywhere in a program without affecting our code.
A comment is preceded by an double forward slash. The code of line after the double forward slash is simply ignored by the compiler.
The are following types of comments in C#

1. Single line comments
// for single line comments

2. Multiple line comments
/* for multi line comments */

3. XML tags comments
/// XML tags displayed in a code comment

  • Use comments only for portions of code that are difficult to understand
  • Comments are used to help document what a program does and what the code with it does. Keep the comments simple and direct. Avoid ASCII art, jokes, poetry and hyper verbosity.
  • During testing, we can comment out lines of code by coding an apostrophe before them. This is useful for testing new statements without deleting the old statement.
    For example:
    protected void Button1_Click(object sender, EventArgs e)
    {
    // On click of button check prior that values are entered properly in order
    }

 

17) C# preprocessor directives.

C# includes a number of commands that are known as preprocessor directives. These commands never actually get translated to any commands in your executable code, but instead they affect aspects of the compilation process.

We could use preprocessor directives to prevent the compiler from compiling code related to the additional features when we are compiling the basic version of the software. Another scenario is that we might have written bits of code that are intended to provide we with debugging information.

The preprocessor directives are all distinguished by beginning with the # symbol.

#define is used like this: #define DEBUG

It is a little bit like declaring a variable, except that this variable doesn’t really have a value — it just exists. And this symbol isn’t part of our actual code; it exists only for the benefit of the compiler, while the compiler is compiling the code, and has no meaning within the C# code itself.

#undef does the opposite, and removes the definition of a symbol:

#undef DEBUG

If the symbol doesn’t exist in the first place, then #undef has no effect. Similarly, #define has no effect if a symbol already exists.

#if, #elif, #else, and #endif. These directives inform the compiler whether to compile a block of code. Consider this method:

int DoSomeWork(double x){

// do something

#if DEBUG

Console.WriteLine(" x is " + x);

#endif

}

This code will compile as normal, except for the Console.WriteLine() method call that is contained inside the #if clause. This line will be executed only if the symbol DEBUG has been defined by a previous #define directive. When the compiler finds the #if directive, it checks to see if the symbol concerned exists

and compiles the code inside the #if clause only if the symbol does exist. Otherwise, the compiler simply ignores all the code until it reaches the matching #endif directive. Typical practice is to define the symbol DEBUG while we are debugging and have various bits of debugging - related code inside #if clauses. Then, when we are close to shipping, you simply comment out the #define directive, and all the debugging code miraculously disappears, the size of the executable fi le gets smaller, and your end users don ’ t get confused by being shown debugging information.

The #elif (=else if) and #else directives can be used in #if blocks and have intuitively obvious meanings.

A symbol is considered to be true if it exists and false if it doesn’t.

Two other very useful preprocessor directives are #warning and #error. These will respectively cause a warning or an error to be raised when the compiler encounters them.

 

 

18) C# programming guidelines.

Identifiers are the names, that we give to variables, to user-defined types such as classes and structs, and to members of these types. Identifiers are case-sensitive, so, for example, variables named interestRate and InterestRate would be recognized as different variables. Rules determining what identifiers we can use in C#:

· They must begin with a letter or underscore, although they can contain numeric characters.

· You can’t use C# keywords as identifiers.

The following table lists the C# reserved keywords.

The convention by which variable names are prefixed with letters that represent the data type is known as Hungarian notation. It means that other developers reading the code can immediately tell from the variable name what data type the variable represents. Hungarian notation is widely regarded as redundant in these days of smart editors and IntelliSense.

 

 

18. C# programming guidelines.

Def: The guidelines is you need to bear in mind when writing C# programs.

Desc: 1) Rules for identifiers. Identifiers are the names you give to variables, to user-defined types such as classes and structs, and to members of these types. Identifiers are case-sensitive. Rules determining what identifiers you can use in C#: They must begin with a letter or underscore, although they can contain numeric characters, You can’t use C# keywords as identifiers. Ex: Name, _Identifier

2) Usage Conventions. In any development language, there usually arise certain traditional programming styles.

Naming Conventions. The general philosophy in the.NET Framework is also that the name of a variable should reflect the purpose of that variable instance and not the data type. Ex: height.

Casing of Names. In many cases you should use Pascal casing for names. Pascal casing means that the fi rst letter of each word in a name is capitalized. Ex: EmployeeSalary. The only other casing scheme that you are advised to use is camel casing. Camel casing is similar to Pascal casing, except that the first letter of the first word in the name is not capitalized. Ex: employeeSalary.

Name Styles. You should be consistent about your style of names. Ex: ShowConfirmationDialog(), ShowWarningDialog()

Namespace Names. it’s almost always a good idea to create a top-level namespacewith the name of your company and then nest successive namespaces that narrow down the technology, group, or department you are working in or the name of the package your classes are intended for.

Ex: WeaponsOfDestructionCorp.Viruses

Names and Keywords. The names do not clash with any keywords. If you attempt to name an itemin your code with a word that happens to be a C# keyword, you’ll almost certainly get a syntax errorbecause the compiler will assume that the name refers to a statement.

Use of Properties and Methods. The rules here are not hard and fast, but in general, you ought to use a property if something really should look and feel like a variable. Otherwise, you should use a method. Ex: Password, SetPassword(). Use of fields. The guidelines are pretty simple here. Fields should almost always be private, except that in some cases itmay be acceptable for constant or read-only fields to be public.

19. Classes in C#.

Def: Classes are essentially templates from which you can create objects. Each object contains data and has methods to manipulate and access that data. The class defines what data and functionality each particular object (called an instance) of that class can contain.

For example, if you have a class that represents a customer, it might define fields such as CustomerID, FirstName, LastName, and Address, which you will use to hold information about a particular customer. It might also define functionality that acts upon the data stored in these fields. You can then instantiate an object of this class to represent one specific customer, set the field values for that instance, and use its functionality.

class PhoneCustomer{

public const string DayOfSendingBill = " Monday";

public int CustomerID;

public string FirstName;

public string LastName; }

Desc: For classes, you use the keyword new to declare an instance. This keyword creates the object and initializes it; in the following example, the default behavior is to zero out its fields:

PhoneCustomer myCustomer = new PhoneCustomer(); // works for a class

The data and functions within a class are known as the class’s members. Microsoft’s official terminology distinguishes between data members and function members. In addition to these members, classes can

contain nested types (such as other classes). Accessibility to the members can be public, protected, internal protected, private, or internal.

 

 

20. Classes' data members in C#.

Def: Data members are those members that contain the data for the class — fields, constants, and events. Data members can be static. A class member is always an instance member unless it is explicitly declared as static.

Desc: Fields are any variables associated with the class. You have already seen fields in use in the PhoneCustomerclass in the previous example.After you have instantiated a PhoneCustomer object, you can then access these fields using the Object.FieldName syntax, as shown in this example:

PhoneCustomer Customer1 = new PhoneCustomer();

Customer1.FirstName = " Simon";

Constants can be associated with classes in the same way as variables. You declare a constant using the const keyword. If it is declared as public, then it will be accessible from outside the class.

class PhoneCustomer

{

public const string DayOfSendingBill = " Monday";

public int CustomerID;

public string FirstName;

public string LastName;

}

Events are class members that allow an object to notify a caller whenever something noteworthy happens, such as a field or property of the class changing, or some form of user interaction occurring. The client can have code, known as an event handler, which reacts to the event.

21. Classes' function members in C#.

Def: Function members are those members that provide some functionality for manipulating the data in the class. They include methods, properties, constructors, finalizers, operators, and indexers.

Desc:Methods are functions that are associated with a particular class. Just as with data members, function members are instance members by default. They can be made static by using the static modifier.

Ex: public bool IsSquare(Rectangle rect){

return (rect.Height == rect.Width); }

Properties are sets of functions that can be accessed from the client in a similar way to the public fields of the class. C# provides a specific syntax for implementing read and write properties on your classes, so you don’t have use method names that have the words Get or Set embedded in them. Because there’s a dedicated syntax for properties that is distinct from that for normal functions, the illusion of objects as actual things is strengthened for client code. Ex: public int Age{ get

{return age; }

set

{age = value; }}

Constructors are special functions that are called automatically when an object is instantiated. They must have the same name as the class to which they belong and cannot have a return type. Constructors are useful for initialization. Ex: public class MyClass{public MyClass(){} // rest of definition}

Finalizers are similar to constructors but are called when the CLR detects that an object is no longer needed. They have the same name as the class, preceded by a tilde (~). It is impossible to predict precisely

when a finalizer will be called.

Operators, at their simplest, are actions such as + or –. When you add two integers, you are, strictly speaking, using the + operator for integers. However, C# also allows you to specify how existing operators will work with your own classes (operator overloading).

Indexers allow your objects to be indexed in the same way as an array or collection.

22. Anonymous types in C#.

Def: When used with the new keyword, anonymous types can be created. An anonymous type is simply a nameless class that inherits from object. The definition of the class is inferred from the initializer, just as with implicitly typed variables.

Desc and Ex: If you need an object that contains a person’s first, middle, and last name, the declaration would look like this:

var captain = new {FirstName = " James", MiddleName = " T", LastName = " Kirk" };

This would produce an object with FirstName, MiddleName, and LastName properties. If you were to create another object that looked like this:

var doctor = new {FirstName = " Leonard", MiddleName = " ", LastName = " McCoy" };

the types of captain and doctor are the same. You could set captain = doctor, for example.

If the values that are being set come from another object, then the initializer can be abbreviated. If you already have a class that contains the properties FirstName, MiddleName, and LastName and you have an instance of that class with the instance name person, then the captain object could be initialized like this:

var captain = new {person.FirstName, person.MiddleName, person.LastName};

The property names from the person object would be projected to the new object named captain. So the object named captain would have the FirstName, MiddleName, and LastName properties.

The actual type name of these new objects is unknown. The compiler “makes up” a name for the type, but only the compiler will ever be able to make use of it. So you can’t and shouldn’t plan on using any type reflection on the new objects because you will not get consistent results.

 

23. Partial classes in C#.

Def: The partial keyword allows the class, struct, method or interface to span across multiple files.

Desc and Ex: Typically, a class will reside entirely in a single file. However, in situations where multiple developers need access to the same class, or more likely in the situation where a code generator of some type is generating part of a class, then having the class in multiple files can be beneficial.

The way that the partial keyword is used is to simply place partial before class, struct, or interface. In the following example, the class TheBigClass resides in two separate source files, BigClassPart1.cs and BigClassPart2.cs: //BigClassPart1.cs partial class TheBigClass{

public void MethodOne(){}}//BigClassPart2.cs partial class TheBigClass{public void MethodTwo(){}}

When the project that these two source files are part of is compiled, a single type called TheBigClass will be created with two methods, MethodOne() and MethodTwo().

If any of the following keywords are used in describing the class, the same must apply to all partials of the same type: ➤ public, ➤ private, ➤ protected, ➤ internal, ➤ abstract, ➤ sealed, ➤ new, ➤ generic constraints

Nested partials are allowed as long as the partial keyword precedes the class keyword in the nested type.Attributes, XML comments, interfaces, generic-type parameter attributes, and members will be combined when the partial types are compiled into the type. Given these two source files: //BigClassPart1.cs

[CustomAttribute] partial class TheBigClass: TheBigBaseClass, IBigClass{public void MethodOne(){}}//BigClassPart2.cs

[AnotherAttribute]partial class TheBigClass: IOtherBigClass

{public void MethodTwo(){}}

after the compile, the equivalent source file would be:

[CustomAttribute][AnotherAttribute]

partial class TheBigClass: TheBigBaseClass, IBigClass, IOtherBigClass

{public void MethodOne(){}

public void MethodTwo(){}}

24.Static classes in C#.

Def: If a class includes nothing but exists static methods and properties, the class will call static. A static class is functionally the same as creating a class with a private static constructor. But static class never can’t be instantiated.

D escry: By using the “static” keyword, the compiler checks existing of instance members. If they exist, a compile show errors. It helps guarantee that an instance is never created. Features of static classes: 1)contains only static members; 2) can’t be instantiated; 3) it’s sealed; 4) can’t contain instance constructors

The syntax for a static class looks like this:

static class StaticUtilities

{ public static void HelperMethod()

{..}

}

Ex: using System; class Program{ static void Main() {// Cannot declare a variable of type Perl. This won't blend. // Program is a regular class so you can create it. Program program = new Program(); // You can call static methods inside a static class. Perl._ok = true; Perl.Blend(); }} static class Perl{ // Cannot declare instance members in a static class! public static bool _ok; // Can only have static methods in static classes. public static void Blend() {Console.WriteLine(" Blended"); }}Output: Blended

25.System.Object class in C#.

Def: All.NET classes are derived from System.Object. System.object includes all classes, structures, enumerations, delegates and etc.. So if you don’t specify a base class when you define a class, the compiler will automatically think that it derives from Object.

Desc:: Every class is actually derived from System.Object. (Note, ex: for structs this derivation is indirect — a struct is always derived from System.ValueType, which in turn derives from System.Object.)The practical goal of this is that, besides the methods and properties and so on that you define, you also have access to a number of public and protected member methods that have been defined for the Objectclass. These methods are available in all other classes that you define:

-ToString()— A fairly basic, quick-and-easy string representation, use it when you just want a quick idea of the contents of an object, perhaps for debugging purposes. It provides very little choice of how to format the data.

-GetHashCode()— If objects are placed in a data structure known as a map (also known as a hash table or dictionary), it is used by classes that manipulate these structures to determine where to place an object in the structure.

-Equals() and ReferenceEquals()— used for comparing the equality of objects.

-Finalize()—this method is intended as the nearest that C# has to C++ style destructors and is called when a reference object is garbage collected to clean up resources.

-GetType()— Returns an instance of a class derived from System.Type sothis object can provide an extensive range of information about the class of which your object is a member, including base type, methods, properties, and so on.

- MemberwiseClone() -It simply makes a copy of the object and returns a reference (or in the case of a value type, a boxed reference) to the copy.

ex:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

{class Program

{static void Main(string[] args)

{var m = Environment.Version;

Console.WriteLine(" Тип m: " +m.GetType());

string s = m.ToString();

Console.WriteLine(" Моя версия.NET Framework: " + s);

Version v = (Version)m.Clone();

Console.WriteLine(" Значение переменной v: " +v);

Console.ReadLine(); } }}

 

 

26. Inheritance in C#.

Def: Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (or pillars) of object-oriented programming. It translated as “NAsledovanie”

Descryp: Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.

Ex: public class Shape;

{ int x, y;

Public virtual string Draw(string Figure)

{Cons.wr.(Figure); }

}

Class Rectangle: Shape

{ public override string Draw(string Name)

{Cons.Wr(“Rectangle”); }

}

 

27.Implementation inheritance in C#.

Def: In object - oriented programming, there are two distinct types of inheritance — implementation inheritance and interface inheritance:

- Implementation inheritance means that a type derives from a base type, taking all the base type ’ s member fields and functions.

Des r: With implementation inheritance, a derived type adopts the base type ’ s implementation of each function, unless it is indicated in the definition of the derived type that a function implementation is to be overridden. This type of inheritance is most useful when you need to add functionality to an existing type, or when a number of related types share a significant amount of common functionality.

Ex: If you want to declare that a class derives from another class, use the following syntax:

class MyDerivedClass: MyBaseClass

{ // functions and data members here}

If a class (or a struct) also derives from interfaces, the list of base class and interfaces is separated by commas:

public class MyDerivedClass: MyBaseClass, IInterface1, IInterface2

{ // etc. }

For a struct, the syntax is as follows:

public struct MyDerivedStruct: IInterface1, IInterface2

{ // etc. }

If you do not specify a base class in a class definition, the C# compiler will assume that System.Object is the base class. Hence, the following two pieces of code yield the same result:

class MyClass // derives from System.Object

{ // etc.}

Because C# supports the object keyword, which serves as a pseudonym for the System.Object class, you can also write:

class MyClass: object // derives from System.Object

{ // etc.}

EX: public class Shape;

{ int x, y;

Public virtual string Draw(string Figure)

{Cons.wr.(Figure); }

}

Class Rectangle: Shape

{ public override string Draw(string Name)

{Cons.Wr(“Rectangle”); }

}

 

28.Interface inheritance in C#.

Def: In object - oriented programming, there are two distinct types of inheritance — implementation inheritance and interface inheritance:

- Interface inheritance means that a type inherits only the signatures of the functions and does not inherit any implementations.

Descry: This type of inheritance is most useful when you want to specify that a type makes certain features available.

Ex: public interface IMyBaseInterface
{void DoA(); }
public interface IMyDerivedInterface
{ void DoB(); }
public class MyClass: IMyDerivedInterface, IMyBaseInterface
{ void DoA();
void DoB(); }

or

publicinterface IA{intProperty1{ get; set; }}publicinterface IB{intProperty2{ get; set; }}publicclass C: IA, IB{publicintProperty1{ get; set; }publicintProperty2{ get; set; }}

 

29.Multiple inheritance in C#.

Def: Some languages such as C ++ support what is known as multiple inheritance, in which a class derives from more than one other class.

Desc: The benefits of using multiple inheritance are debatable: On one hand, there is no doubt that it is possible to use multiple inheritance to write extremely sophisticated, yet compact, code, as demonstrated by the C ++ ATL library. On the other hand, code that uses multiple implementation inheritance is often diffi cult to understand and debug (a point that is equally well - demonstrated by the C ++ ATL library). As mentioned, making it easy to write robust code was one of the crucial design goals

behind the development of C#. Accordingly, C# does not support multiple implementation inheritance. It does, however, allow types to be derived from multiple interfaces — multiple interface inheritance. This means that a C# class can be derived from one other class, and any number of interfaces. Indeed, we can be more precise: Thanks to the presence of System.Object as a common base type, every C# class (except for Object) has exactly one base class, and may additionally have any number of base interfaces.

Ex: public class MyDerivedClass: MyBaseClass, IInterface1, IInterface2

{ // etc. }

30.Virtual methods in C#.

Def: A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overriden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overriden in the derived class using the override keyword.

Descryp: When a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the derived class to override that method. The overriding method also provides more than one form for a method. Hence it is also an example for polymorphism.

When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the derived class. 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.

Program cant use private virtual method, because virtual or abstract members cannot be private. And after compiling you’ll have error.

Ex: public class Shape;

{ int x, y;

Public virtual string Draw(string Figure)

{Cons.wr.(Figure); }

}

Class Rectangle: Shape

{ public override string Draw(string Name)

{Cons.Wr(“Rectangle”); }

 

31. Abstract classes and functions in C#.

C# allows both classes and functions to be declared as abstract. The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class. An abstract class cannot be instantiated, whereas an abstract function does not have an implementation, and must be overridden in any non-abstract derived class. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. Obviously, an abstract function is automatically virtual (although you don’t need to supply the virtual keyword; doing so results in a syntax error). If any class contains any abstract functions, that class is also abstract and must be declared as such:

abstract class Triangle{

public abstract decimal CalculateArea(); // abstract method

}

 

 

32. Modifiers in C#.

modifiers — keywords that can be applied to a type or to a member.

Access Modifiers: public - The item is visible to any other code.

protected - The item is visible only to any derived type. internal - The item is visible only within its containing assembly. private - The item is visible only inside the type to which it belongs. protected internal - The item is visible to any code within its containingassembly and also to any code inside a derived type.

Example: public class MyClass{// etc.}

Modifiers that indicate the nature of an item:

Abstrac t- Indicates that a class is intended only to be a base class of other classes. Const - Specifies that the value of the field or the local variable cannot be modified. New- Hides an inherited member from a base class member. Override - Provides a new implementation of a virtual member inherited from a base class.

Partial - Defines partial classes, structs and methods throughout the same assembly.

Sealed - Specifies that a class cannot be inherited.

Static - Declares a member that belongs to the type itself instead of to a specific object.

Virtua l - Declares a method or an accessor whose implementation can be changed by an overriding member in a derived class.

extern -The member is implemented externally, in a different language.

class MyBaseClass {

public virtual string VirtualMethod() {

return " This method is virtual and defined in MyBaseClass"; } }

class MyDerivedClass: MyBaseClass {

public override string VirtualMethod() {

return “This method is an override defined in MyDerivedClass.”; } }

 

33. Interfaces in C#.

Interface names start with I. Interface can only contain declarations of methods, properties, indexers, and events.You can never instantiate an interface; it contains only the signatures of its members. An interface hasneither constructors (how can you construct something that you can’t instantiate?) nor fields (because thatwould imply some internal implementation). An interface definition is also not allowed to contain operatoroverloads it is becauseinterfaces are usually intended to be public contracts, and having operator overloads would cause someincompatibility problems with other.NET languages, such as Visual Basic.NET, which do not supportoperator overloading.It is also not permitted to declare modifiers on the members in an interface definition. Interface members arealways implicitly public, and cannot be declared as virtual or static Example:

public interface IDisposable

{void Dispose(); }

class SomeClass: IDisposable

public void Dispose()

{// implementation of Dispose() method}

// rest of class}

Derived interfaces

It’s possible for interfaces to inherit from each other in the same way that classes do. For example, let define new interface, ITransferBankAccount, which has the same features as IBankAccount but also defines a method to transfer money directly to a different account:

namespace Wrox.ProCSharp

{

public interface ITransferBankAccount: IBankAccount

{bool TransferTo(IBankAccount destination, decimal amount);

}}

Because ITransferBankAccount is derived from IBankAccount, it gets all the members of IBankAccount as well as its own. That means that any class that derives from ITransferBankAccount must implement all the methods of IBankAccount, as well as the new TransferTo() method defined in ITransferBankAccount.

34. Generics in C#.

With generics, you can create classes and methods that are independent of

contained types. Instead of writing a number of methods or classes with the same functionality for different types, you can create just one method or class. Generics introduce to the.NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. Generic types are used to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes.

Example: / / Declare the generic class.

public class GenericList< T>

{void Add(T input) { }

}

class TestGenericList

{ private class ExampleClass { }

static void Main()

{// Declare a list of type int.

GenericList< int> list1 = new GenericList< int> ();

// Declare a list of type string.

GenericList< string> list2 = new GenericList< string> ();

// Declare a list of type ExampleClass.

GenericList< ExampleClass> list3 = new GenericList< ExampleClass> ();

}

}

Performance: Boxing and unboxing are easy to use but have a big performance impact.Generic allows you to define the type when it is used. In the example here, the generic type of the List < T > class is defined as int, so the int type is used inside the class that is generated dynamically from the JIT compiler. Boxing and unboxing no longer happens

Type Safety: With the generic class List< T>, the generic type T defines what types are allowed. With a definition of List< int>, only integer types can be added to the collection.

Дополнительно var list = new List< int> ();

list.Add(44);

list.Add(" mystring"); // compile time error

list.Add(new MyClass()); // compile time error

Binary code reuse: Generics allow better binary code reuse. A generic class can be defined once and can be instantiated with many different types.

Code Bloat: when the generic classes are compiled by the JIT

compiler to native code, a new class for every specific value type is created. Reference types share all the same implementation of the same native class.

 

35. Creating generic classes in C#.

Def: Generics introduce to the.NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. Generic types are used to maximize code reuse, type safety, and performance.

Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on. Operations such as adding and removing items from the collection are performed in basically the same way regardless of the type of data being stored.When creating generic classes, important considerations include the following:

a. As a rule, the more types we can parameterize, the more flexible and reusable your code becomes. However, too much generalization can create code that is difficult for other developers to read or understand.

b. A good rule is to apply the maximum constraints possible that will still let you handle the types you must handle.

c. Whether to factor generic behavior into base classes and subclasses.Because generic classes can serve as base classes, the same design considerations apply here as with non-generic classes. See the rules about inheriting from generic base classes later in this topic.

d. Whether to implement one or more generic interfaces.

class BaseNode { }

class BaseNodeGeneric< T> { }

 

// concrete type

class NodeConcrete< T>: BaseNode { }

 

//closed constructed type

class NodeClosed< T>: BaseNodeGeneric< int> { }

 

//open constructed type

class NodeOpen< T>: BaseNodeGeneric< T> { }

36. Generics features in C#.

When creating generic classes, you might need some more C# keywords.

a. Default values: - It is not possible to assign null to generic type

- We can use default keyword to initialize default(either 0 or null) value

b. Constraints – If Generic class needs to invoke some methods from the generic type we have to add constraints.

where T: struct With a struct constraint, type T must be a value type.

where T: class Class constraint indicates that type T must be a reference type.

where T: IFoo where T: IFoo specifies that type T is required to implement interface IFoo.

where T: Foo where T: Foo specifi es that type T is required to derive from base class Foo.

where T: new() where T: new() is a constructor constraint and specifies that type T must have a default constructor.

where T1: T2 With constraints it is also possible to specify that type T1 derives from a generic

type T2. This constraint is known as naked type constraint.

c. Inheritance: - A generic type can implement a generic interface.

- When deriving from generic base class, you must provide a type argument instead of the base-class’s generic type parameter.

public class LinkedList< T>: IEnumerable< T>

{//...

A generic type can implement a generic interface. The same is possible by deriving from a class. A generic class can be derived from a generic base class:

public class Base< T> { }

public class Derived< T>: Base< T> { }

the derived class can be a generic or non-generic class. For example, you can define an abstract generic base class that is implemented with a concrete type in the derived class. This allows you to do specialization for specific types:

public abstract class Calc< T>

{

public abstract T Add(T x, T y);

public abstract T Sub(T x, T y);

}

public class IntCalc: Calc< int>

{

public override int Add(int x, int y)

{

return x + y;

}

public override int Sub(int x, int y)

{

return x — y;

}

}

d. Static Members – static members of generic class are only shared with one instatiation of the class.

 

37. Generic interfaces in C#.

Def. It is often useful to define interfaces either for generic collection classes, or for the generic classes that represent items in the collection.

Desc The preference for generic classes is to use generic interfaces, such as IComparable< T> rather than IComparable, in order to avoid boxing and unboxing operations on value types. The.NET Framework class library defines several generic interfaces for use with the collection classes in the System.Collections.Generic namespace. When an interface is specified as a constraint on a type parameter, only types that implement the interface can be used.

Example:

class Stack< T> where T: System.IComparable< T>, IEnumerable< T>

{

}

 

38. Generic methods in C#.

Def: Generic methods can be defined within non – generic classes. A generic method can be invoked by assigning the generic type with the method call:

int i = 4;

int j = 5;

Swap< int> (ref i, ref j);

However, because the C# compiler can get the type of the parameters by calling the Swap() method, it is






© 2023 :: MyLektsii.ru :: Мои Лекции
Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав.
Копирование текстов разрешено только с указанием индексируемой ссылки на источник.