简体   繁体   中英

creating instance of the class

I was about to start learning C# and came across zetcode C# tutorial (any suggestion for the nice tutorial website or pdf is appreciated). Since I was doing some programming using Python before, I found C# not so difficult. But, one thing I little confusing to me is the use of something like this taken from that website.

using System;

public class Being {}

public class CSharpApp
{
    static void Main()
    {
        Being b = new Being();// I don't understand this
        Console.WriteLine(b);
    }
}

Why not just:

b=new Being ();

Why is the website using the name of the class while in two places? Is it just the way C# is or is it one way of writing it?

well, you have 2 parts to it there.

The first part is the declaration of b

Being b;

Which essentially tells the compiler that you're going to be using a variable of type Being with the name b


The second part is the assignment of b

b = new Being();

Which assigns the variable b with an object, which in this case, is a new instance of the Being class


c# allows you to combine both parts into 1 line, resulting in the following:

Being b = new Being();

The first "Being" defines the type of the variable b . This says that " b is a reference to an object of type Being ". You could change this to var b = Being() and the compiler will infer the type of B based on the expression on the right hand side of the equals sign.

The second "Being" is part of an expression that provides the initial value of the variable b . In this case, it's a call to the default constructor Being() . You could assign the value of b in many ways:

Being b = null; // don't give it any value yet
Being b = new Being(); // make a new Being object using the default constructor
Being b = new Being("abcde"); // use a different custom constructor
Being b = GiveMeABeing(); // call some other method that will return a Being object

The first Being in the variable declaration tells the compiler how it may identify and handle the object. The new Being() tells the compiler how to build (instantiate) the object. This sort of thing is useful when you leverage interfaces and subclasses.

abstract class IMusicalInstrument {
  public Play();
}

class Trumpet : IMusicalInstrument {
  public Play() {
    // etc.
  }
}

class Piano : IMusicalInstrument {
  public Play() {
    // etc.
  }
}

In doing so, you can leverage methods that return an unknown IMusicalInstrument :

IMusicalInstrument instrument = GetARandomInstrument();

.. And rest assured that you can Play() them, despite not knowing exactly what they are.

The first line is defining a class

public class Being {}

and second code is creating an instance of that class.

Being b = new Being()

Why not just:

b = new Being(); ?

I assume that you have knowledge about = operator which assigns rhs to lhs. In above statement you're assigning something to b right?

How does compiler knows what is b ? Compiler has no idea what is b ! So you have to say that b is a local variable of type Being that is what the following code doing

Being b;

Now nothing is in b You wanna store something in b in order to use it right? So create a instance of type Being and store it. that is what the following code doing

b = new Being();

We merge both and tell to compiler that b is of type Being and it holds new instance of Being .

Being b = new Being();

Hope this helps

That's the way C# works. You need to give the name of the class. If you don't like that syntax - you can also do:

var being = new Being();

You have to declare the type and then instantiate the type, so in your example you would specify that you want to declare a Being and then actually create (read: new up) a Being object.

As to your question of why you need to specify it twice, your declaration type could be a base class, but you instantiate a derived class, like this:

public class Animal {}

public class Human : Animal {}

Now in your code you could declare an Animal , but actually instantiate a Human , because a Human is an Animal , like this:

Animal myHuman = new Human();

Objects in C# are modeled after real life objects. For instance, a ball has a radius, bounciness, weight, color, etc. You can also perform actions on a ball such as throwing, rolling, dropping, spinning, etc. In C#, you would create a class definition like this for a ball:

public class Ball
{
    // Radius in inches
    public double Radius { get; set; }
    public double Bounciness { get; set; }
    // Weight in lbs
    public double Weight { get; set; }
    public string Color { get; set; }
    // more properties

    // constructor - this is called when your class is instantiated (created)
    public Ball()
    {

    }

    // throw the ball
    public void Throw()
    {
        // method for throwing ball
    }

    // roll the ball
    public void Roll()
    {
        // method for rolling ball
    }

    // drop the ball
    public void Drop()
    {
        // method for dropping ball
    }

    // spin the ball
    public void Spin()
    {
        // method for spinning the ball
    }

    // more methods for interacting with a ball
}

Then you would declare an instance of Ball, set properties and call methods like this:

Ball ball = new Ball();
ball.Color = "Red";
ball.Weight = 1.2; // 1.2 lbs
ball.Radius = 12; // 12 inches
ball.Bounciness = 0.2; // for use in a physics engine perhaps
ball.Throw(); // throw the ball
ball.Drop(); // drop the ball
// etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM