Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet26/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   22   23   24   25   26   27   28   29   ...   78
Bog'liq
C sharp

 Default Constructor
It is possible to create a class even if no constructors are defined. This 
is because the compiler will automatically add a default parameterless 
constructor to such a class. The default constructor will instantiate the 
object and set each field to its default value.
class MyRectangle {}
class MyApp
{
static void Main()
{
// Calls default constructor
MyRectangle r = new MyRectangle();
}
}
 Object Initializers
When creating an object, as of C# 3.0, it is possible to initialize the object’s 
public fields within the instantiation statement. A code block is then 
added, containing a comma-separated list of field assignments. This object 
initializer block will be processed after the constructor has been called.
class MyRectangle
{
public int x, y;
}
Chapter 10 Class


55
class MyClass
{
static void Main()
{
// Use object initializer
MyRectangle r = new MyRectangle() { x = 10, y = 5 };
}
}
If there are no arguments for the constructor, the parentheses may be 
removed.
MyRectangle r = new MyRectangle { x = 10, y = 5 };
 Partial Class
A class definition can be split up into separate source files by using the 
partial type modifier. These partial classes will be combined into the 
final type by the compiler. All parts of a partial class must have the partial 
keyword and share the same access level.
// File1.cs
public partial class MyPartialClass {}
// File2.cs
public partial class MyPartialClass {}
Splitting classes across multiple source files is primarily useful when 
part of a class is generated automatically. For example, this feature 
is used by Visual Studio’s graphical user interface builder to separate 
automatically generated code from user-defined code. Partial classes can 
also make it easier for multiple programmers to work on the same class 
simultaneously.
Chapter 10 Class


56

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   22   23   24   25   26   27   28   29   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling