Sunteți pe pagina 1din 12

Types and variables There are two kinds of types in C#: value types reference types.

Variables Variables Variables Variables of of of of value types directly contain their data. value types have their own copy of the data. reference types store references to their data(objects). reference types may reference the same object.

C#'s value types includes: simple types enum types struct types nullable types C#'s reference types are: class types interface types array types delegate types. The following table lists the concrete types and their group names: Signed integral sbyte, short, int, long Unsigned integral byte, ushort, uint, ulong Unicode characters char IEEE floating point float, double High-precision decimal decimal Boolean bool Enum enum EnumTypeName {...} Struct struct StructTypeName {...} Nullable value type nullable value

Value type vs reference type The variables of value type store the real value, while the reference type varia bles store the references to the real objects. Reference type A reference type variable has two parts: the object and its address. A reference type variable stores the address of the object, not the object itsel f.

null reference value A reference type variable can be assigned to null. null means the reference type variable points to nothing. A value type variable cannot be assigned to null.

Predefined data types C# defines the following data types: sbyte short int long byte ushort uint ulong float double decimal bool char string sbyte, short, int and long are singed integer type. byte, ushort, unit and ulong are unsigned integer types Predefined C# types have alias in System namespace. For example, the alias for int type is System.Int32

Numeric types The following table lists the numeric types in C#: C# type sbyte short int long byte ushort uint ulong float double decimal System type System.SByte System.Int16 System.Int32 System.Int64 System.Byte System.UInt16 System.UInt32 System.UInt64 System.Single System.Double System.Decimal Size 8 bits 16 bits 32 bits 64 bits 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits 128 bits Range -27 to 27-1 -215 to 215-1 -231 to 231-1 -263 to 263-1 0 to 28-1 0 to 216-1 0 to 232-1 0 to 264-1 +/- (~10-45 to 1038) +/-(~10-324 to10308) +/- (~10-28 to 1028)

Literal suffix You can use suffix to define literals explicitly. The following table lists the suffix used by C#. Letter F D M U L C# type float double decimal uint or ulong long or ulong Example f = 1.0F; d = 1D; decimal d = 1.0M; uint i = 1U; ulong i = 1UL;

char escape sequence Some characters are not typeable from keyboard directly. For example, the new li ne character. In such circumstance we use escape sequence to represent the special character v alue. An escape sequence starts with backslash. Char \' \" \\ \0 \a \b \f \n \r \t \v Meaning Single quote Double quote Backslash Null Alert Backspace Form feed New line Carriage return Horizontal tab Vertical tab Value 0x0027 0x0022 0x005C 0x0000 0x0007 0x0008 0x000C 0x000A 0x000D 0x0009 0x000B

What is an Array C# array stores a list of variables in the same type. The length of an array is fixed. Array type is declared by putting square brackets after the data type. C# array is inherited from System.Array. Array elements can be of any type, including an array type. System.Array implements IEnumerable and IEnumerable<T>, you can use foreach iter ation on all arrays in C#. Arrays are zero indexed: an array with n elements is indexed from 0 to n-1. The default value of numeric array elements are set to zero, and reference eleme nts are set to null. An array can be Single-Dimensional, Multidimensional or Jagged. A jagged array is an array of arrays, and therefore its elements are reference t ypes and are initialized to null. The size of an array is declared when allocating memory for its elements. In C#, arrays are actually objects. System.Array is the abstract base type of all array types. Jagged array A jagged array is an array whose elements are arrays. Jagged array is an array of array. Each inner array dimension can be declared af ter the outter dimension has been initialized. The elements of a jagged array can be of different dimensions and s izes. The following is a declaration of a single-dimensional array that has three elem ents, each of which is a single-dimensional array of integers:

nt[][] jaggedArray = new int[3][]; Before you can use jaggedArray, its elements must be initialized. You can initia lize the elements like this: jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2]; You can int[][] { new new new }; also initialize the array upon declaration like this: jaggedArray = new int[][] int[] {1,3,5,7,9}, int[] {0,2,4,6}, int[] {11,22}

A jagged array elements are reference types and are initialized to null. You can access individual array elements like these examples: jaggedArray3[0][1] = 7; jaggedArray3[2][1] = 8; It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains three two-dimensional array elements of different sizes. int[][,] jaggedArray = new int[3][,] { new int[,] { {1,3}, {5,7} }, new int[,] { {0,2}, {4,6}, {8,10} }, new int[,] { {1,2}, {9,8}, {0,9} } };

Ternary operator The ternary operator has the following form: question ? expression1 : expression2 It can be rewritten as: if (question == true){ expression1; }else { expression2; }

Flow control statements C# has the following statements to do the flow control. Selection statement if switch

? : Loop statement while do...while for foreach Jump statement break continue throws return goto

Classes and Structs Classes and structs are a data structure that encapsulates a set of data and beh aviors. A class is a reference type. A struct is a value type. Class and Struct Accessibility Classes and structs that are declared directly within a namespace can be either public or internal. Internal is the default if no access modifier is specified. Struct members, including nested classes and structs, can be declared as public, internal, or private. Class members, including nested classes and structs, can be public, protected in ternal, protected, internal, or private. The access level for class members and struct members, including nested classes and structs, is private by default. Derived classes cannot have greater accessibility than their base types. You can enable specific other assemblies to access your internal types by using the InternalsVisibleToAttribute. Class and Struct Member Accessibility Class members including nested classes and structs can be declared with any of t he five types of access. Struct members cannot be declared as protected because structs do not support in heritance. User-defined operators must always be declared as public. Destructors cannot have accessibility modifiers. The following code adds the Access Modifiers to the class public class Rectangle { // protected method: protected void calculate() { } // private field: private int width = 3; // protected internal property: protected internal int Width { get { return width; } }

} You can specify how accessible your types and their members are by using the acc ess modifiers. The access modifiers are public protected internal protected internal private. Members Classes and structs have members that represent their data and behavior. The following table lists the kinds of members a class or struct may contain: Member Description Fields Fields are variables declared at class scope. Constants Constants are fields or properties whose value is set at compile time and cannot be changed. Properties Properties are methods that are accessed as if they were fields. Methods Methods define the actions that a class can perform. Events Events provide event notifications. Operators Overloaded operators. Indexers Indexers enable an object to be indexed in a manner similar to a rrays. Constructors Constructors are methods that are called when the object is firs t created. Destructors Destructors are methods that are called by the runtime when the object is about to be removed from memory. Nested Types Nested types are types declared within another type.

Read only field A read only field is declared with readonly modifier. A read only field cannot change its value after declaration or outside the const ructors. A readonly field cannot be assigned to (except in a constructor or a variable in itializer).

Methods Fields are the data of a type(class) while the methods define the behaviours. A method contains a series of statement. A method can also get input from outside by declaring parameters and output to o utside by returning value. The void return type indicates that no value will return from the method. A method's signature is its name and parameters' type.

A method's signature must be unique within its type(class). A method can have the following modifiers: static, public, internal, private, protected, new, virtual, abstract, override, sealed, unsafe, extern C# requires that local variable must have assigned value.(intr-o metoda de exemp lu, ca acea variablia sa poata fi folosita. Daca nu este folosita, poate fi lasata neinitializata. Daca o varia bila nu este initializa intr-o clasa, ea poate fi folosita intr-o metoda dar se trimite un warning)

Method overloading Methods can have the name but different parameter types. The following code defines a class, Math. Math has two methods with the same name. It is legal since the signatures are di fferent. params is not part of the signature. You will get a Compile-time error The return type is not part of the signature. You will also get an error(cant ha ve same method name with different return types) ref and out modifiers are part of the method signature.

Static constructor Each type can have only one static constructor. static constructor have no parameters and it is execuated per type not per insta nce. static constructor is called by C# when initializing the type or calling its sta tic members. It can only have extern and unsafe modifier.

Inheritance Classes (but not structs) support the concept of inheritance. A class that derives from the base class automatically has all the public, prote cted, and internal members of the base class except its constructors and destructors. In C# one class can only inherit from a single class. Up casting is a cast towards its super class or parent class. Down cast happens when casting to subclass or child class. Down cast needs an ex plicit cast.

virtual members A virtual member can be overriden by its subclasses. A virtual member is marked by the virtual keyword. A virtual feature can be a method, a property, an indexer or an event.

Abstract class Abstract class can have abstract members(are cel putin un membru abstract. Se po ate scapa fara nici un membru abstact daca se creaza un mebru virtual. Metodele virtuale si abstracte pot fi d oar publice). Abstract method have no method body. Abstract class declares a blue print for a type. Abstract class cannot be instantiated.

Static Class Classes (but not structs) can be declared as static. A static class can contain only static members and cannot be instantiated with t he new keyword. One copy of the class is loaded into memory when the program loads, and its memb ers are accessed through the class name. Both classes and structs can contain static members. A static class can contain only static members. We cannot instantiate the class using a constructor. We must refer to the members through the class name. Static Members A non-static class can contain static methods, fields, properties, or events. The static member is callable even when no instance of the class has been create d. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in thei r containing type. Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class. C# does not support static local variables. Static members are initialized before the static member is accessed for the firs t time and before the static constructor is called.

as and is as operator as operator does the down cast. Rather than throws exception out it assigns the reference to null. is operator is operator tells if a reference is a certain class.

Class object instance Creating Objects A class defines a type of object, but it is not an object itself. An object is an instance of a class. Objects can be created by using the new keyword followed by the name of the clas s. Rectangle object1 = new Rectangle(); object1 is a reference to an object based on Rectangle. object1 refers to the new object but does not contain the object data itself. In fact, you can create an object reference without creating an object at all: Rectangle object2; A reference can be made to refer to an object, either by creating a new object, or by assigning it to an existing object, such as this: Rectangle object3 = new Rectangle(); Rectangle object4 = object3; This code creates two object references that both refer to the same object. Therefore, any changes to the object made through object3 will be reflected in s ubsequent uses of object4. Because objects that are based on classes are referred to by reference, classes are known as reference types.

Struct Instances vs. Class Instances Classes are reference types. A variable of a class object holds a reference to the object. Two class variables may refer to the same object. Instances of classes are created by using the new operator. In the following example, Person is the type and person1 and person2 are instanc es, or objects, of that type. Structs are value types. A variable of a struct object holds a copy of the entire object. Instances of structs can also be created by using the new operator, but this is not required. Daca avem doua obiecte de tipul unei structuri. In caz ca se modifica membrii un uia dintre obiecter, aceste

modificari nu au loc si pentru celalat obiect pt ca obiectele de tipul unei stru cturi sunt copii, nu referinte ca in cazul unei clase.

Boxing and unboxing Boxing is the process of casting value type to reference type. Unboxing casts the reference type to value type. The following code is boxing the i to object. int i = 0; object obj = i; The unbox requires an explicit cast. int i = 0; object obj = i; int j = (int)obj;

GetType and typeof operator GetType does the runtime check while the typeof operator does the compile-time c heck. Both GetType and typeof return System.Type.

Structs Structs share most of the same syntax as classes. Within a struct declaration, fields cannot be initialized unless they are declar ed as const or static. A struct may not declare a default constructor (a constructor without parameters ) or a destructor. When a struct is assigned to a new variable, all the data is copied. Any modification to the new copy does not change the data for the original copy. Structs are value types and classes are reference types. Structs can be instantiated without using a new operator. Structs can declare constructors that have parameters. A struct cannot inherit from another struct or class. A struct cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.O bject. Structs can implement interfaces. Structs can be used as a nullable type and can be assigned a null value. A struct is a value type and it doesn't support inheritance and virtual or abstr

act members. The struct cannot have finalizer.

interface An interface defines a series of members the implementer must implement. An interface itself doesn't provide any implementation. A class can implement any number of interfaces. A struct can implement interface as well. An interface can only have methods, properties, events and indexers. interface is extendable.(ca si o clasa. Cand o clasa mosteneste o alta clasa, ac easta ii mareste gradul de functionalitate. Cand o alta clasa o mosteneste p a doua, are in acest fel acces si la campurile primei clase.)

enum type An enum type defines a group of constants. Each constant has a name and backend numeric value. An enum is a value type. The operators that work with enums are: = == != < > <= >= + - ^ & ? += -= ++ sizeof. Enums can be of type byte, sbyte, short, ushort, int, uint, long, ulong An enum value is convertable to its underline numeric value. int i = (int)WeekDay.Monday; We can even convert integer back to enum value. WeekDay day = (WeekDay)2;

Generic type Classes and structs can be defined with one or more type parameters. Client code supplies the type when it creates an instance of the type. For example, the List<T> class in the System.Collections.Generic namespace is de fined with one type parameter.

Client code creates an instance of a List<string> or List<int> to specify the ty pe that the list will hold. Generic type is a type with type parameter. The type parameter is only a place holder. Only method, class, interfce, delegate and struct can have type parameters. Other member can only reference them.

Delegate A delegate is a type for method. Delegate defines a way we should follow to create methods. Then later we can use the delegate type to reference the methods with the same f orm. We can use delegate as a type for method parameter. C# overloads the + and - operators for delegate. By using + and - we can add methods to or subtract methods from a delegate type variable. The delegates are called in the sequence of adding. delegate can have generic type.

Event and delegate C# formalizes the event handling by using delegate. It uses event keyword to declare a delegate type as the event listener and all d elegate instances as the handler. event can have the following modifiers. virtual overridden abstract sealed static http://java2s.com/Book/CSharp/0060__Collections/0080__Array.htm http://www.scribd.com/doc/517796/Manual-C

S-ar putea să vă placă și