C# Class Examples

Array Collections File String Windows VB.NET Algorithm ASP.NET Cast Class Compression Convert Data Delegate Directive Enum Exception If Interface Keyword LINQ Loop Method .NET Number Regex Sort StringBuilder Struct Switch Time Value

Class conceptual illustration

Immense complexity is managed in computer programs. Clever abstractions make this possible. The class construct reduces programs to simple conceptual units that are independent yet connected. Classes are built into interconnected models. These models closely reflect the problems we try to solve.

Attribute Examples Constructor Tips Object Type Property Examples

A type is a concrete representation of a concept. A class is a user-defined type. Stroustrup, p. 223

Syntax

This short program demonstrates how you can create a custom class (Example) and also a custom constructor and a property. The constructor here receives one integer parameter. The property here has a private setter, and a public getter and uses the concise syntax form.

Program that demonstrates class [C#]

using System;

class Example
{
    public Example(int property)
    {
	Property = property;
    }
    public int Property { get; private set; }
}

class Program
{
    static void Main()
    {
	Example example = new Example(5);
	Console.WriteLine(example.Property);
    }
}

Program

5

Overview: These C# examples cover the class keyword. Classes are reference types and are instantiated.

Constructors. It is common to need to have different ways of instantiating a class. If you use the class in many places, you may want to create overloaded constructors that are flexible for the contexts you instantiate the class. Please note that there are also other syntax forms you can use to implement overloaded constructors, which use the base and this keywords.

Constructor Tips

This example 1

This keyword

In C# class bodies, you can use the this keyword before a field, method, or property identifier. The this keyword in this context is called an instance expression. In most cases, you can omit the 'this'; the keyword is only useful in cases where an ambiguity would arise.

Program that reveals instance expression [C#]

using System;

class Perl
{
    string _name;
    public Perl()
    {
	// Assign this._name
	this._name = "Perl";
	// Assign _name
	_name = "Sam";

	// The two forms reference the same field.
	Console.WriteLine(this._name);
	Console.WriteLine(_name);
    }
}

class Program
{
    static void Main()
    {
	Perl perl = new Perl();
    }
}

Output

Sam
Sam

This example 2

There is another way to use the 'this' instance expression in a C# class. You can pass the 'this' instance to another method, which will then receive the reference to the class you called it from. This can be useful in some contexts where you have a chain of method calls and constructors.

This Instance
Program that uses this as argument [C#]

using System;

class Net
{
    public string Name { get; set; }
    public Net(Perl perl)
    {
	// Use name from Perl instance.
	this.Name = perl.Name;
    }
}

class Perl
{
    public string Name { get; set; }
    public Perl(string name)
    {
	this.Name = name;
	// Pass this instance as a parameter!
	Net net = new Net(this);
	// The Net instance now has the same name.
	Console.WriteLine(net.Name);
    }
}

class Program
{
    static void Main()
    {
	Perl perl = new Perl("Sam");
    }
}

Output

Sam

Namespace

Namespaces in the C# language are exclusively an organizational feature. Often, programs will have namespaces containing their classes, but this simply changes the syntax forms and ways of identifying the target classes. There is no semantic or functional change provided by namespaces.

Namespace Examples

Static class

Static illustration

The term static refers to a position that is unchanging or fixed. A static class in the C# language cannot be instantiated; its position in memory is therefore fixed in one place. For more information on static classes, please visit the targeted article.

Static Class Static Modifier

Static constructor. Static constructors are not exclusive to static classes, but they are often used with them. They give you a way to execute code when a static class is first used. They don't really have much to do with instance constructors, and are just a separate feature. They also hide some complexity that can result in bugs.

Static Constructor

Inheritance

Inheritance is an important feature of the class model in the C# language. You can use inheritance to simplify your program and make it easier to add new features. There is more information on inheritance, and the related concepts of type derivation and polymorphism, on this site.

Inheritance Explanation

Derived class example

When you have a derived class, you can use the base expression to access the base class directly. This example demonstrates the difference between the base keyword and the this keyword. You can use these keywords to resolve ambiguous expressions in your class definitions.

Program that uses base and this keywords [C#]

using System;

class Net
{
    public int _value = 6;
}

class Perl : Net
{
    public new int _value = 7;
    public void Write()
    {
	// Show difference between base and this.
	Console.WriteLine(base._value);
	Console.WriteLine(this._value);
    }
}

class Program
{
    static void Main()
    {
	Perl perl = new Perl();
	perl.Write();
    }
}

Output

6
7

Private example

Question and answer

What is the difference between private and public classes in the C# programming language? Classes are by default private. When you specify that a class is public, you can then instantiate it in external locations. In this example code, we show how you can instantiate a nested class only if it specifies that it is in the public accessibility domain.

Program that shows how to use nested class [C#]

using System;

class Test
{
    class Subclass
    {
    }
    public class Pubsubclass
    {
    }
}

class Program
{
    static void Main()
    {
	// Cannot instantiate Subclass here!
	// ... But can instantiate Test.Pubsubclass!
	Test.Pubsubclass pub = new Test.Pubsubclass();
    }
}

Result
    (The nested class is instantiated.)

Internal classes. There are also other accessibility domains in the C# programming language that you can use to control where your types can be instantiated. One such modifier is the internal keyword, and it requires that a class be only instantiated in the same program or library.

Internal

Nested classes. Nested classes are determined by the lexical position of type declarations in your source files. It is important to distinguish nested classes from derived classes and member fields.

Nested Class

Members

Examples

Classes would be pretty useless without members: these are fields, methods, and properties that provide storage for data or behaviors to act upon that data. One important feature in the C# language is the property, which gives you a way to add executable code in a syntax form that resembles a simple memory access.

Fields. Continuing on, classes contain fields, which are locations in memory where data is stored for each class instance. Fields can have modifiers and different accessibility levels. They can be initialized as well.

Protected Modifier Readonly Fields Public Static Readonly Field Variable Initializer for Class Field

Indexers. One particularly interesting type of member on a class is an indexer. You can use an indexer by directly using the class instance with array syntax. We dive into indexers in more detail.

Indexer Example

Operator overloading. For some types, it makes sense to overload operators. This means you can add classes together, or use other unary or binary operators upon them.

Operator Overloading

Generic class

Generic type

If you see the < and > tokens in a class declaration, it is a generic class. Inside the < and > tokens are the type parameters to the class. This concept and its usage is described further on this site.

Generic Class Type Parameter Constraints: Generics

Modifiers

Class methods introduce behavior—but no persistent data—to our class definitions. Methods are called to act upon the data inside the class, and can also be called with parameters to influence their actions.

Private Method Public Method

Class modifiers. These articles cover class modifiers. An internal class is a class that is isolated to a specific program. You cannot access it from an external program or method. The sealed keyword is used to specify that a class cannot be derived from.

Abstract Keyword Partial Class Sealed Keyword

OOP

Object-oriented programming

What is the point of object-orientation anyways? I attempt to describe why you would want to use this style of programming in your projects. We also deal with some concepts of OOP in general.

Object-Oriented Programming Benefits Factory Pattern Protection Proxy Design Pattern

Summary

The C# programming language

With classes, you can create instances of custom types in your C# programs. This gives you an almost unlimited power to model real-world data with custom types, in a way that is very maintainable and easy to understand. In this example set, we demonstrated many conceptual aspects of classes, from their constructors to their derivation semantics and syntax forms.

Dot Net Perls