1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

How to create a class in C Sharp 4.0

Discussion in 'C#' started by arunlalds, Mar 12, 2010.

  1. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    Problem: You need to create a class declaration.
    Code:
    //default namespace to import, that Visual Studio includes in each file
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace ClassSample
    {
    //public so that it's visible outside of assembly
    public class Vertex3d
    {
    }
    }
    
    
    The class is defined as public, which means it is visible to every other type that references
    its assembly. C# defines a number of accessibility modifiers, as detailed as follows: Public= Types members Accessible to everybody, even outside the assembly Private= Types, members Accessible to code in the same type Internal= Types, members Accessible to code in the same assembly Protected= Members, Accessible to code in the same type or derived type Protected Internal= Members Accessible to code in the same assembly internal or a derived class in another assembly If the class does not specify the accessibility, it defaults to internal.
     
  2. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Define Fields, Properties, and Methods in C Sharp 4.0

    Let's add some usefulness to the Vertex3d class.
    Code:
    public class Vertex3d
    {
    //fields
    private double _x;
    private double _y;
    private double _z;
    //properties
    public double X
    {
    get { return _x; }
    set { _x = value; }
    }
    public double Y
    {
    get { return _y; }
    set { _y = value; }
    }
    public double Z
    {
    get { return _z; }
    set { _z = value; }
    }
    //method
    public void SetToOrigin()
    {
    X = Y = Z = 0.0;
    }
    }
    
    
    Some notes on the preceding code:
    1. The fields are all declared private, which is good practice in general.
    2. The properties are declared public, but could also be private, protected, or protected internal, as desired.
    3. Properties can have get, set, or both.
    4. In properties, value is the implied argument (that is, in the code).
    In the following example, 13.0 would be passed to X in the value argument:
    Vertex3d v = new Vertex3d();
    v.X = 13.0;
     
  3. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    Use Auto-Implemented Properties

    You will often see the following pattern:
    Code:
    class MyClass
    {
    private int _field = 0;
    public int Field { get { return _field; } set { _field = value; } }
    }
    C# has a shorthand syntax for this:
    class MyClass
    {
    public int Field {get; set;}
    //must initialize value in constructor now
    public MyClass()
    {
    this.Field = 0;
    }
    }
    
    
     
  4. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Define Static Members in C Sharp 4.0

    Add the modifying keyword static, as in the following method for adding
    two Vertex3d objects:
    Code:
    public class Vertex3d
    {
    ...
    public static Vertex3d Add(Vertex3d a, Vertex3d b)
    {
    Vertex3d result = new Vertex3d();
    result.X = a.X + b.X;
    result.Y = a.Y + b.Y;
    result.Z = a.Z + b.Z;
    return result;
    }
    }
    
    
    The static method is called like in this example:
    Vertex3d a = new Vertex3d(0,0,1);
    Vertex3d b = new Vertex3d(1,0,1);
    Vertex3d sum = Vertex3d.Add(a, b);
     
  5. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Add a Constructor in C Sharp 4.0

    Define a special method, called a constructor, with the same name as the class, with no return type. A constructor runs when a type is created—it is never called directly. Here are two constructors for the Vertex3d class—one taking arguments, the other performing some default initialization.

    Code:
    class Vertex3d
    {
    public Vertex3d()
    {
    _x = _y = _z = 0.0;
    }
    public Vertex3d(double x, double y, double z)
    {
    this._x =x;
    this._y = y;
    this._z = z;
    }
    }
    
    Add a Static Constructor and Initialization
    Static fields can be initialized in two ways. One way is with a static constructor, which is similar to a standard constructor, but with no accessibility modifier or arguments:
    Code:
    public class Vertex3d
    {
    private static int _numInstances;
    static Vertex3d()
    {
    _numInstances = 0;
    }
    ...
    }
    
    However, because of performance reasons, it is preferable to initialize static fields inline whenever possible, as shown here:
    Code:
    public class Vertex3d
    {
    private static int _numInstances = 0;
    ...
    }
    
     
  6. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Initialize Properties at Construction in C Sharp 4.0

    Use object initialization syntax, as in the following example:
    Code:
    class Person
    {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    }
    ...
    Person p = new Person()
    { Id = 1, Name = “Ben”, Address = “Redmond, WA” };
    
     
  7. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Use const and readonly in C Sharp 4.0

    Both const and read only are used to define data that does not change, but there are important differences: const fields must be defined at declaration. Because of this and the fact that they cannot change value, it implies that they belong to the type as static fields. On the other hand, read only fields can be set at declaration or in the constructor, but nowhere else.
    Code:
    public class Vertex3d
    {
    private const string Name = “Vertex”;
    private readonly int ver;
    public Vertex3d()
    {
    ver = Config.MyVersionNumber;//Ok
    }
    public void SomeFunction()
    {
    ver = 13;//Error!
    }
    }
    
     
  8. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Reuse Code in Multiple Constructors in C Sharp 4.0

    Problem: You have multiple constructors, but they have a subset of functionality that is common among them. You want to avoid duplicating code. In C++ and some previous languages, you often had the case where a class with multiple constructors needed to call common initialization code. In these cases, you usually factored out the common code into a common function that each constructor called.
    Code:
    //C++ example
    class MyCppClass
    {
    public:
    MyCppClass() { Init(); }
    MyCppClass(int arg) { Init(); }
    private:
    void Init() { /* common init here*/ };
    }
    Solution: In C#, you are allowed to call other constructors within the same class
    using the this keyword, as shown next:
    public class Vertex3d
    {
    public Vertex3d(double x, double y, double z)
    {
    this._x = x;
    this._y = y;
    this._z = z;
    }
    public Vertex3d(System.Drawing.Point point)
    :this(point.X, point.Y, 0)
    {
    }
    ...
    }
    
     
  9. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Derive from a Class in C Sharp 4.0

    You need to specialize a class by adding and/or overriding
    behavior.
    Use inheritance to reuse the base class and add new functionality.
    Code:
    public class BaseClass
    {
    private int _a;
    protected int _b;
    public int _c;
    }
    public class DerivedClass : BaseClass
    {
    public DerivedClass()
    {
    _a = 1;//not allowed! private in BaseClass
    _b = 2;//ok
    _c = 3;//ok
    }
    public void DoSomething()
    {
    _c = _b = 99;
    }
    }
    
    Deriving from a class gives access to a base class's public and protected members, but
    not private members.
     
  10. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Call a Base Class Constructor in C Sharp 4.0Similar to calling other construct

    Similar to calling other constructors from the constructor of a class, you can call specific constructors of a base class. If you do not specify a constructor, the base class’s default constructor is called. If the base class’s default constructor requires arguments, you will be required to supply them.
    Code:
    public class BaseClass
    {
    public BaseClass(int x, int y, int z)
    { ... }
    }
    public class DerivedClass : BaseClass
    {
    public DerivedClass()
    : base(1, 2, 3)
    {
    }
    }
    
     
  11. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Override a Base Class’s Method or Property in C Sharp 4.0

    The base class’s method or property must be declared virtual and
    must be accessible from the derived class. The derived class will use the override
    keyword.
    Code:
    public class Base
    {
    Int32 _x;
    public virtual Int32 MyProperty
    {
    get
    {
    return _x;
    }
    }
    public virtual void DoSomething()
    {
    _x = 13;
    }
    }
    public class Derived : Base
    {
    public override Int32 MyProperty
    {
    get
    {
    return _x * 2;
    }
    }
    public override void DoSomething()
    {
    _x = 14;
    }
    }
    
    Base class references can refer to instances of the base class or any class derived from
    it. For example, the following will print “28,” not “13.”
    Code:
    Base d = new Derived();
    d.DoSomething();
    Console.WriteLine(d.MyProperty().ToString());
    
    You can also call base class functions from a derived class via the base keyword.
    Code:
    public class Base
    {
    public virtual void DoSomething()
    {
    Console.WriteLine(“Base.DoSomething”);
    }
    }
    public class Derived
    {
    public virtual void DoSomething()
    {
    base.DoSomething();
    Console.WriteLine(“Derived.DoSomething”);
    }
    }
    
    Calling Derived.DoSomething will print out the following:
    Code:
    Base.DoSomething
    Derived.DoSomething
    
    Overriding Non-virtual Methods and Properties
    You can still override it, but with a caveat: The override method will only be called through a reference to the derived class. To do this, use the new keyword (in a different context than you're probably used to).
    Code:
    class Base
    {
    public virtual void DoSomethingVirtual()
    {
    Console.WriteLine(“Base.DoSomethingVirtual”);
    }
    public void DoSomethingNonVirtual()
    {
    Console.WriteLine(“Base.DoSomethingNonVirtual”);
    }
    }
    class Derived : Base
    {
    public override void DoSomethingVirtual()
    {
    Console.WriteLine(“Derived.DoSomethingVirtual”);
    }
    public new void DoSomethingNonVirtual()
    {
    Console.WriteLine(“Derived.DoSomethingNonVirtual”);
    }
    }
    class Program
    {
    static void Main(string[] args)
    {
    Console.WriteLine(“Derived via Base reference:”);
    Base baseRef = new Derived();
    baseRef.DoSomethingVirtual();
    baseRef.DoSomethingNonVirtual();
    Console.WriteLine();
    Console.WriteLine(“Derived via Derived reference:”);
    Derived derivedRef = new Derived();
    derivedRef.DoSomethingVirtual();
    derivedRef.DoSomethingNonVirtual();
    }
    }
    
    Here is the output of this code:
    Derived via Base reference:
    Derived.DoSomethingVirtual
    Base.DoSomethingNonVirtual
    Derived via Derived reference:
    Derived.DoSomethingVirtual
    Derived.DoSomethingNonVirtual

    Make sure you understand why the output is the way it is.
     
  12. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Create an Interface in C Sharp 4.0

    Here’s a sample interface for some kind of playable object—perhaps an audio or video file, or even a generic stream. An interface does not specify what something is, but rather some behavior.
    Code:
    public interface IPlayable
    {
    void Play();
    void Pause();
    void Stop();
    double CurrentTime { get; }
    }
    
    Note that interfaces can contain methods as well as properties. You do not specify access with interfaces’ members because, by definition, they are all public.
     
  13. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Implement Interfaces in C Sharp 4.0

    A class can implement multiple interfaces, separated by commas:
    Code:
    public class AudioFile : IPlayable, IRecordable
    {
    ...
    }
    
    However, you may run into instances where two (or more) interfaces define the same method. In our small example, suppose both IPlayable and IRecordable have a Stop() method defined. In this case, one interface must be made explicit.
    Code:
    public class AudioFile : IPlayable, IRecordable
    {
    void Stop()
    {
    //IPlayable interface
    }
    void IRecordable.Stop()
    {
    //IRecordable interface
    }
    }
    
    Here is how to call these two methods:
    Code:
    AudioFile file = new AudioFile();
    file.Stop();//calls the IPlayable version
    ((IRecordable)file).Stop();//calls the IRecordable version
    
    Note that we arbitrarily decided that IRecordable’s Stop() method needed to be explicit—you could just have easily decided to make IPlayable’s Stop() method the explicit one.
     
  14. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    How to Create a Struct in C Sharp 4.0

    Unlike in C++, where structs and classes are functionally identical, in C#, there are
    important and fundamental differences:
    1. Structs are value types as opposed to reference types, meaning that they exist on the stack. They have less memory overhead and are appropriate for small data structures. They also do not have to be declared with the new operator.
    2. Structs cannot be derived from. They are inherently sealed
    3. Structs may not have a parameterless constructor. This already exists implicitly and initializes all fields to zeros.
    4. All of a struct’s fields must be initialized in every constructor.
    5. Structs are passed by value, just like any other value-type, in method calls.
    6. Beware of large structs.
    Solution: Defining a struct is similar to a class:
    Code:
    public struct Point
    {
    private Int32 _x;
    private Int32 _y;
    public Int32 X
    {
    get { return _x; }
    set { _x = value; }
    }
    public Int32 Y
    {
    get { return _y; }
    set { _y = value; }
    }
    public Point(int x, int y)
    {
    _x = x;
    _y = y;
    }
    public Point() {} //Not allowed!
    //Not allowed either! You're missing _y’s init
    public Point(int x) { this._x = x; }
    }
    
    They can be used like so:
    Code:
    Point p;//allocates, but does not initialize
    p.X = 13;//ok
    p.Y = 14;
    Point p2 = new Point();//initializes p2
    int x = p2.X;//x will be zero
    
     
  15. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,292
    Likes Received:
    365
    Trophy Points:
    83

Share This Page