Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of "Class" in C# [closed]

Tags:

c#

While studying C# in ASP.net I have trouble understanding several classes. In which scenario should I use the following classes private,public,protected,abstract,static,sealed ?

It would be better if someone can explain these with easy examples.

like image 906
Nazmul Avatar asked Jun 22 '10 06:06

Nazmul


2 Answers

Those are not classes.

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 static members.

I suggest you start with "Getting Started with Visual C#. This is a very basic question.

like image 121
John Saunders Avatar answered Oct 07 '22 06:10

John Saunders


public, private and protected aren't classes, they're access modifiers. They change what is allowed to access the classes that you decorate with them. They apply to classes as well as the members of classes.

  • public items can be seen from anywhere
  • private classes can only be seen from within the same file
  • private members of classes can only be seen within that class
  • protected members are visible from within the class and its descendants
  • internal classes are public within the same assembly.

The abstract keyword marks a class or method as having no implementation, and it must be overridden (with the override keyword) in a derived type before you can use it.

A sealed class cannot be inherited from.

Using the static keyword on a class member indicates that the member belongs to the class itself, rather than a specific instance of it. Marking a class as static imposes the restriction that all members of this class must also be static.

like image 35
Eltariel Avatar answered Oct 07 '22 06:10

Eltariel