C# Class

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

Class

A program is an abstract machine. Its parts are in movement as it executes. Its parts are called classes.
These building blocks stand alone,
but together,
they form complex models. With classes our abstract machine stores data and thinks.

Example

Let us start at the beginning. That is the best place to start. This program shows many concepts of the C# language. It has a custom class (Example). That class has a constructor and a property.

Constructor:The constructor uses the same name as the class (Example). This one receives an int parameter.

Property:We also see a property, named "Property," with the concise syntax form for a getter and a setter.

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

Constructor

New keyword, constructor invocation

We often need to have different ways of instantiating a class. We might use the class in many places. With overloaded constructors, we can add many entry points for creating the class. This makes programs better.

Constructor

Also:There are other syntax forms we use to implement overloaded constructors. These forms use the "base" and "this" keywords.

This

This keyword

In class bodies, we use the "this" keyword before a field, method or property identifier. The "this" keyword in this context is called an instance expression. In most places, though, we can omit the "this."

This

So:The keyword is only useful in cases where an ambiguity between two variables 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
Method call

Also, there is another way to use the "this" instance expression in a class. We can pass the "this" instance to another method. That method will then receive the reference to the class we called it from.

Tip:This approach can be useful in some contexts where you have a chain of method calls and constructors.

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

Object

Object keyword

Every class is derived from the ultimate base class—object. Because of this, every variable can be cast to an object reference. This makes it possible to treat any variable as one type.

However:Using only objects is not desirable because it makes the program more complex and less efficient.

Object

Namespace

Chaos

Namespaces are exclusively an organizational feature. Often, programs will have namespaces containing their classes. But this simply changes the syntax forms. It alters how we must identify a target class.

Info:A namespace adds no features to a program.
It provides no semantic or functional changes.

Namespace

Static

Static

The word "static" refers to a position that is unchanging, fixed. A static class in the C# language cannot be instantiated. Its position in memory is therefore fixed in one place.

Static ClassStatic

Static constructors are not exclusive to static classes. But they are often used in static classes. They execute code when a static class is first used. They are not connected to instance constructors—they are a separate feature.

Also:Static constructors mask some complexity, such as the order of execution. This can result in bugs.

Static Constructor

Inheritance

Concept

Inheritance is an important feature of the class model. We use inheritance to simplify a program—to make it easier to add new features. We explore inheritance, and the related concepts of type derivation and polymorphism.

Inheritance

Polymorphism:This is a good word to make yourself sound smart. But it also refers to a way we use many "forms" of a single object.

Derived

Class

When we have a derived class, we can use a "base" expression to directly access the base class. This example demonstrates the difference between "base" and "this." The syntax is similar, but the meaning is different.

Tip:We use these keywords to resolve ambiguous expressions in 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

Question

What is the difference between private and public? Classes are by default private. Programmers are less likely to misuse private classes. When we make a class public, we can instantiate it in external locations.

Next:We show how to instantiate a nested class. The nested class must be in the public accessibility domain.

Nested:A nested class is determined by the lexical position of type declarations in your source files.

Nested Class
Program that uses a 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.)

Property

Property

Properties are an important feature in the language. They give us a way to add executable code in a syntax form that resembles a simple memory access. They have other uses, such as in data-binding.

Property

Indexer:An indexer is a type of property. It is used with simple syntax—the same syntax used for array accesses.

Indexer

Fields

Copy: new object copied

Classes contain fields. In fields, we access memory that can store data for each class instance. Fields have modifiers and accessibility levels. They can be initialized in the class itself.

ProtectedReadonlyPublic Static ReadonlyVariable Initializer

Ordering:Does the ordering of fields affect memory usage?
I investigate further.
It does not matter how we order our fields.

Field Ordering

Operators

Operator keyword

For some types, it make sense to overload operators. An overloaded operator can make syntax simpler. You can add classes together. You can use unary or binary operators upon classes.

Operator

Generics

Generic type

If you see the < and > tokens in a class declaration, it is a generic class. Those tokens contain the type parameters to the class. Generic classes are powerful. In the .NET Framework, popular types such as Dictionary are generics.

Generics

Modifiers

A class can have modifiers. These influence how the class may be used. A public class can be anywhere in your project. A private one is more restricted. An abstract class is used only as a template for other classes.

PrivatePublicQuestion

Internal:We can apply the internal keyword to a class. It requires that a class be only instantiated in the same program or library.

Internal

Abstract:An abstract class cannot be directly instantiated. It is used, in derivation, to create other classes.

Abstract

Partial:A partial class is contained in more than one file. This is a feature used often by Visual Studio in Windows Forms.

Partial

Sealed:The sealed keyword is used to specify that a class cannot be derived from.

Sealed

Attribute

Attribute Flags syntax

An attribute is attached to a type such as a class. It becomes part of the metadata. It is used to influence the compiler's behavior on the type. This makes it possible for types to be changed with no runtime cost.

Attribute

OOP

Object-oriented programming

What is the point of object-orientation? I attempt to describe why you would want to use this style of programming in projects. I also explore some concepts and design patterns of OOP.

OOPFactoryProxy

Summary

C# programming language

With classes we create instances of custom types in C# programs. This gives an almost unlimited power to model real-world data. Class-based models are easier to understand. With them, we tame the dragon of complexity.

Review:A class has a constructor.
It has derivation semantics.
It has many syntax forms.

C#