Pages

Wednesday, June 29, 2011

Access Modifiers in C# Are Easy To Understand with the Right Examples

private, protected and public are access modifiers. They indicate which other code can see the code they affect:

public class Foo
{
    private int _myOwn = 1;
    protected int _mineAndChildren = 2;
    public int _everyOnes = 3;
}

public class Bar : Foo
{
    public void Method()
    {
        _myOwn = 2; // Illegal - can't access private member
        _mineAndChildren = 3; // Works
        _everyOnes = 4; // Works
    }
}

public class Unrelated
{
    public void Method()
    {
        Foo instance = new Foo();
        instance._myOwn = 2; // Illegal - can't access private member
        instance._mineAndChildren = 3; // Illegal
        instance._everyOnes = 4; // Works
    }
}

An abstract class is one that may contain abstract members. An abstract member has no implementation, so all derived classes must implement the abstract members.

A sealed class cannot be inherited. A static class is sealed, but also can only contain staticmembers.

No comments:

Post a Comment