Travis J
Travis J

Reputation: 82297

Can constructorless classes have their methods called without instantiation?

Can I avoid initializing this?

I have a simple factory with no constructor. I use it like this:

var slf = new GenericSelectListFactory();
vm.Works = slf.getWorkgsl(0);
vm.Cars = slf.getCargsl(0);

I can also use it like this:

vm.Cars = new GenericSelectListFactory().getCargsl(0);

Is there any way to use it without the new keyword?

vm.Cars = GenericSelectListFactory.getCargsl(0);

Upvotes: 1

Views: 402

Answers (4)

James Johnson
James Johnson

Reputation: 46067

A class without a constructor is assigned a default constructor by the compiler, mainly to eliminate the need for empty constructors:

Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation.

If you want to access the methods without initializing the class, make the method(s) static. In doing this though, you should ensure that the methods are thread safe.

Upvotes: 3

Alois Kraus
Alois Kraus

Reputation: 13545

Make the method of your class static.

class GenericSelectListFactory
{
   public static List<Cars> getCargsl()
   {
      // your logic here
   }

}

Upvotes: 9

Sanjeev
Sanjeev

Reputation: 1575

you can make the functions static.

Upvotes: 2

cichy
cichy

Reputation: 10644

without "new" you should mark method as static

Upvotes: 4

Related Questions