Continous staff improvement project
CLASSES IN C#
SERGIU GRAJDEAN
OBJECTIVES
• CLASSES IN C#
• FIELD, METHOD, PROPERTY
• CONSTRUCTORS
• ACCESS MODIFIERS
• READONLY VS CONST
• OVERLOADING
• INHERITANCE
• VIRTUAL METHODS
• SEALED MODIFIER
• ABSTRACT CLASSES AND ABSTRACT MEMBERS
• INTERFACES
• STRUCTS
CLASSES IN C#
• A class is a construct that enables you to create your own custom types by
grouping together variables of other types, methods and event
• Declare a class :
class User
{
}
• Create instance of class:
User user = new User();
FIELD
• A field is a variable that is a member of a class or struct
• Declare fields :
class User
{
int age;
public string Name;
int accountBalance = 10;
}
• Fields initialization and usage:
User user = new User { Name = "john Smith" };
user.name = "John Smith";
METHOD
• A method is a code block that contains a series of statements
• Declaration:
class User
{
public string Name;
int accountBalance = 10;
public void Withdraw(int valueToWithdraw)
{
accountBalance -= valueToWithdraw;
}
public bool CanWithdraw(int valueToWithdraw)
{
return accountBalance >= valueToWithdraw;
}
}
METHOD
• Method usage:
User user = new User { Name = "john Smith" };
bool canWidthdraw = user.CanWithdraw(9);
if (canWidthdraw)
{
user.Withdraw(9);
}
PROPERTY
• A property is a member that provides a flexible mechanism to read, write, or
compute the value of a private field
• Declaration:
class User
{
string name;
public string Name
{
get{return name;}
set{name = value;}
}
//…more code
}
PROPERTY
• Property usage
User user = new User { Name = "john Smith" };
user.Name = "John Smith";
string userName = user.Name;
PROPERTY VS FIELD
• Fields must be always keep private, e.g. in C++
class User
{
private:
std::string name;
public:
void setName(const std::string &newName){ name = newName; }
std::string getName(){ return name; }
};
• Java
public class Printer {
private String name;
public void setName(String newName){name=newName;}
public String getName(){return name;}
}
AUTO-IMPLEMENTED PROPERTIES
• In C# 3.0 and later, auto-implemented properties make property-declaration more
concise when no additional logic is required in the property accessors
• Declaration
class User
{
public string Name
{
get;
set;
}
//…more code
}
READ-ONLY & SET-ONLY PROPERTY
• A property is read-only if it specifies only a get accessor
class User
{
int accountBalance = 10;
public int AccountBalance{ get{ return accountBalance; }}
//… more code
}
• A property is write-only if it specifies only a set accessor
class User
{
string password;
public string Password{set{password = value;}}
//… more code
}
CALCULATED PROPERTY
class User
{
public int BirthYear;
public int Age
{
get{return DateTime.Now.Year - BirthYear;}
set{BirthYear = DateTime.Now.Year - value; }
}
}
CONSTRUCTORS
• Constructors run initialization code on a class or struc
• compiler automatically generates a parameterless public constructor if and only if
you do not define any constructor
class User
{
int accountBalance = 10;
public User(){}
public User(string name, int balance)
{
Name = name;
accountBalance = balance;
}
public string Name { get; set; }
//… more code
CONSTRUCTOR AND FIELD INITIALIZATION ORDER
• Field initializations occur before the constructor is executed, and in the
declaration order of the fields
class User
{
int accountBalance = 10; // Initialized first
string password = "secret1"; // Initialized second
public User(string name, int balance)
{
Name = name;
accountBalance = balance;
}
public string Name { get; set; }
//… more code
OBJECT INITIALIZERS
• Any accessible fields or properties of an object can be set via an object initializer
directly after construction
• Usage
User user = new User { Name = "John Smith", AccountBalance = 20,
Age=25};
• Equivalent
User temp = new User();
temp.Name = "John Smith";
temp.AccountBalance = 20;
temp.Age = 25;
User user = temp;
ACCESS MODIFIERS
• Access modifiers are keywords used to specify the declared accessibility of a
member or a type
• public : Access is not restricted
• protected : Access is limited to the containing class or types derived from the
containing class
• Internal : Access is limited to the current assembly
• private : Access is limited to the containing type
• Protected internal: The type or member can be accessed by any code in the
assembly in which it is declared, or from within a derived class in another
assembly
• Private protected: The member is accessible by types derived from the
containing class, but only within its containing assembly.
ACCESS MODIFIERS
• Usage
internal class User // internal if not specified
{
int accountBalance = 10; // private if not specified
private string password = "secret1";
protected string Password{set{password = value;}}
public string Name { get; set; }
protected internal void ResetPassword() {/*... more code */}
}
READONLY MODIFIER
• The readonly keyword is a modifier that you can use on fields
• The readonly modifier prevents a field from being modified after construction
internal class User
{
readonly List<Order> orders = new List<Order>();
public User()
{
orders = new List<Order>();
}
void AddOrder(Order order)
{
orders = new List<Order>(); // compile time error
}
//… more code
CONST MODIFIER
• Constant fields and locals aren't variables and may not be modified
internal class User
{
public const int DeafaultBalance = 10;
int accountBalance = DeafaultBalance;
//…more code
}
• Usage
int defaultBalance = User.DeafaultBalance;
READONLY VS CONST
• Const are fully evaluated at compile time
• Const are faster
• Const may be inlined by the compiller
• Const doesn’t allow ref type initialization
• Const is always static
• Const is copied into every assembly that uses them (every assembly gets a local
copy of values)
• Can be used in attributes
• Readonly allows ref type initialization
• Readonly may be either per instance or per class (static)
• Readonly is initialized once at run time
OVERLOADING
• A type may overload methods (have multiple methods with the same name), as
long as the signatures are different
• Valid declaration
public class MyClass
{
void Foo(int x) {...}
void Foo(double x) {...}
void Foo(int x, float y) {...}
void Foo(float x, int y) {...}
}
• Invalid declaration
void Foo(int x) {...}
float Foo(int x) {...} // Compile-time error
void Goo(int[] x) {...}
void Goo(params int[] x) {...} // Compile-time error
INHERITANCE
• A class can inherit from another class to extend or customize the original class.
• Declaration
public class Geometry
{
public void Draw() {}
}
public class Rectangle : Geometry
{
public int Width { get; set; }
public int Height { get; set; }
}
INHERITANCE
• Usage
Geometry geometry = new Geometry();
geometry.Draw();
Rectangle rectangle = new Rectangle();
rectangle.Draw();
int height = rectangle.Height;
int width = rectangle.Width;
Geometry rectGeometry = rectangle;
rectGeometry.Draw();
• Once child class is converted to parent type all its members become invisible
Rectangle rectangle = new Rectangle();
Geometry rectGeometry = rectangle;
rectGeometry.Draw();
rectGeometry.Width; // compile time error
VIRTUAL METHODS
• A function marked as virtual can be overridden by subclasses wanting to provide
a specialized implementation
public class Geometry
{
public virtual void Draw() { }
public virtual void Invalidate() { }
}
public class Rectangle : Geometry
{
public override void Draw()
{
// draw code
base.Draw();
}
}
VIRTUAL METHODS
• In a virtual method invocation, the run-time type of the instance for which that
invocation takes place determines the actual method implementation to invoke
void DrawGeometry(Geometry geometry)
{
geometry.Invalidate();
geometry.Draw();
}
SEALED MODIFIER
• When applied to a class, the sealed modifier prevents other classes from
inheriting from it
• When an instance method declaration includes a sealed modifier, that method is
said to be a sealed method
class A
{
public virtual void Foo(){}
}
class B : A
{
public sealed override void Foo(){}
}
sealed class C
{
}
ABSTRACT CLASSES AND ABSTRACT MEMBERS
• A class declared as abstract can never be instantiated
public abstract class Geometry
{
public virtual void Draw(){}
public virtual void Invalidate() { }
}
Geometry geometry = new Geometry(); // compile time error
• Abstract classes are able to define abstract members. Abstract members are like virtual members,
except they don’t provide a default implementation.
public abstract class Geometry
{
public abstract void Draw();
public virtual void Invalidate() { }
}
ABSTRACT CLASSES AND ABSTRACT MEMBERS
• Subclasses must implement all abstract methods unless they are not abstract
public class Rectangle : Geometry
{
public override void Draw()
{
}
}
INTERFACES
• Interface members are all implicitly abstract. In contrast, a class can provide both
abstract members and concrete members with implementations
• A class can implement multiple interfaces. In contrast, a class can inherit from
only a single class
public interface IGeometry
{
void Draw();
void Invalidate();
}
public abstract class Geometry : IGeometry
{
public abstract void Draw();
public virtual void Invalidate() { }
}
STRUCTS
• A struct is similar to a class, with the following key differences:
• A struct is a value type, whereas a class is a reference type
• A struct does not support inheritance (other than implicitly deriving from object, or
more precisely, System.ValueType)
• A struct can have all the members a class can, except the following:
• A parameterless constructor
• A finalizer
• Virtual members
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
ASSIGNMENT
• CREATE A C# PROGRAM WHICH USES CLASSES TO MODEL REAL
WORLD OBJECTS
• USE METHODS AND FIELDS TO ENCAPSULATE CLASS
IMPLEMENTATION
• USE PROPERTIES TO MAKE SOME PROPERTIES ACCESSIBLE OR
REPLACE TRIVIAL METHODS (GETTERS/SETTERS)
• CREATE A CLASS HIERARCHY TO MODEL REAL WORLD
HIERARCHIES (ANIMALS IN ZOO, SHAPES IN DRAWING SYSTEM,
ETC)
• CREATE A METHOD AND MAKE ITS OVERLOADED AND
OVERRIDDEN VERSIONS
REFERENCES
• Albahari J, Albahari B (2012). C# 5.0 in a Nutshell.
• MSDN
REVISIONS
Number Author Date Description
1.0.0 Serghei Grajdean 07.12.2015 Initial version
1.0.1 Serghei Grajdean 12.02.2016 Minor changes
1.1.0 Serghei Grajdean 19.02.2016 Sealed modifier
added