开发者

create an object with out new keyword in c#

  public class Animal
    {

        public void Eat()
        {
            Console.Wri开发者_运维技巧teLine("Animal eats for living.");
        }
    }

Animal a = new Animal();

is it really required to use new keyowrd when we instantiate an object ?

can we do like this

Animal a = Animal();

any help here would be great.


No. You can always use Activator - Activator.CreateInstance. Not sure if you would actually find it simpler than new though.

Also looking at your example, you probably want to make it static as your methods are not acting on a specific instance of your class. That ways you can directly call Animal.Eat().

  public static class Animal
  {

        public static void Eat()
        {
            Console.WriteLine("Animal eats for living.");
        }
   }


To instantiate an object yes you always need to use new. That being said, if for somereason you don't like that you could create a static load method in your class that contains the new keyword. This doesn't change the fact that you are using new but it does hide it. Something like this:

public class Animal
{
    private Animal(){}
    public static Animal Load()
    {
         return new Animal();
    }
    public void Eat()
    {
        Console.WriteLine("Animal eats for living.");
    }
}

Or you could just make a static class.


You probably have C++ in mind, for which there's a difference between instantiating an object with or without new.

This does not apply in C#. "Animal" is always a reference to the object. If the C# syntax allowed to write "Animal a = Animal();", that would likely be meaning exactly the same as "Animal a = new Animal();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜