Lesson 4
In this lesson we’ll learn how to create your own types.
Agenda
- Class example
- Access modifiers
- Static
- Static Constructors
- C# Coding Conventions
- References
- Presentation
Class example
It’s been said in lesson 1 that class is a ‘description’ for objects. When you define a class, you define a blueprint for an object.
Basically class consists of:
- Class name
- Constructors. They are used to create and initialize any object member variables when you use the ‘new’ expression to create an object of a class.
- Members. It’s some variable inside a class.
- Properties. A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field.
- Methods (functions). A function allows you to encapsulate a piece of code and call it from other parts of your code.
Following example demonstrates a class with all its basic features:
And it can be used in following way:
Access modifiers
- public: access is not restricted
- private: access is limited to the containing type
- protected: access is limited to the containing class or types derived from the containing class
- internal: access is limited to the current assembly
- protected internal: access is limited to the current assembly or types derived from the containing class
Static
Static member in class belongs to the type itself, not to a specific object. Static member or function can be defined with ‘static’ modifier.
Example of static class:
And its using example:
Static constructors
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced. Static constructor defines with out any access modifier.
Static class is demonstrated in the Calculator example above:
C# Coding Conventions
Such guidelines are used by Microsoft. It’s kindly recommended to use it o your projects.
References
Access modifiers are keywords used to specify the declared accessibility of a member or a type. This section introduces the four access modifiers:
- Constructor
- Methods
- Functions
- Properties
- Access Modifiers
- [Static Classes and Static Class Members]
- static-classes-and-static-class-members
- Static Constructors
- C# Coding Conventions