How to Create a Class in C#
If you're an experienced programmer or have some knowledge of Java or C++, it should be simple to create a class in C#. While the mechanism and conventions for doing so are very similar to creating a class in these programming language, C# handles inheritance more like Java than C++. In C# all classes inherit from a single base class. However, you can change the accessibility of the class simply by using one of C#'s seven modifier keywords in the header.
Instructions
-
Create a Class
-
1
Give the class a meaningful name. This name will be used as the identifier for the class when creating instances of the class or creating new subclasses. Although it is not required, C# convention calls for capitalization of the first letter in a class name.
-
2
Precede the class name with the "class" keyword. The class keyword lets the compiler know that you are defining a new class and that the following code block is not a function definition. For instance: "class Vehicle"
-
-
3
Enclose the body of the class in curly braces. The body will include any data member declarations, class methods, or nested internal classes, as demonstrated in the following example: "class Vehicle { // data members and method definitions go here }"
-
4
Precede the class keyword in the header with one of seven modifier keywords if access to the class is required. Internal is the default access for a class in C#. If no modifier is used, a class has internal access. Internal classes are only accessible from other classes in the same assembly.
Use Modifiers
-
5
Use the "new" modifier with nested classes (classes defined in the body of another class). New means that the class includes a member that is inherited and has the same name.
-
6
Ensure that the class in only accessible from within the class in which it is defined by using the "private" modifier. Like new, this modifier is also used with nested classes.
-
7
Use the "protect" modifier to make sure that nested classes accessible from within the outer class, but also from any class that inherits from the outer class.
-
8
Ensure that no subclasses that inherit from the sealed class can be defined by preceding the class keyword with the "public class" modifier. For example" "public class Vehicle { // data members and methods // this class is accessible from any other class in a program }"
-
1
Tips & Warnings
A public class is accessible from any other class in a program.
Comments
-
expertelement
Jan 20, 2009
Why is the relationship expert writing about c#? -
expertelement
Jan 20, 2009
Why is the relationship expert writing about c#?