How to pass object as parameter in c#

10,197

Solution 1

In your scenario you've specified VehicleType as a name of the variable declared with a type object. You can't instantiate objects like this.

If you can provide more information on your problem, I'll try to provide a more specific answer.

For instance you could add a new property to your Vehicle class called VehicleType and it would be of type enum.

Or maybe you'd like to implement factory pattern and use interfaces for dealing with a collection if you need multiple types of a vehicle in one collection.

edit based on the comments:

There are multiple ways of doing this, so I mention the one that wasn't mentioned by others so far. It's based on reflection. Basically you search your assembly for classes that inherit your "superclass" and if their name corresponds with the supplied parameter, instantiate it.
However, we can simplify this process by using a class called Activator. All we need is the name of the assembly containing the desired class and it's name. Activator will create its instance for us.

Here's one sample to get you started:

public static SuperClass GetClass(string type)
{
   return (SuperClass)Activator.CreateInstance("someAssemblyName", "type");
}

Or more info from MSDN: http://msdn.microsoft.com/en-us/library/b4wc81dc.aspx

Of course you can modify the properties prior to any further actions, maybe something like this:

public static SuperClass GetClass(string type, string brand, string model)
{
   SuperClass sc = (SuperClass)Activator.CreateInstance("someAssemblyName", "type");
   sc.Brand = brand;
   sc.Model = model;

   return sc;
}

Solution 2

If you are going for a Factory approach, then use it as a factory. A static class, that constructs stuff for. No more, no less. Don't put state in that factory for storing objects (the list V).

Then the somewhat debatable static method

static void AddNewVehicle(object VehicleType, string brand, string model, int year, int price)
{
    V.Add(new VehicleType(brand, model, year, price));
}

What are you trying to do here? You pass an object with the name VehicleType, yet you want to construct a new one in the body?

Then the compiler error:

The type or namespace name 'VehicleType' could not be found (are you missing a using directive or an assembly reference?)

That means you either:

  • don't have a class with the name VehicleType
  • don't have a using statement that includes the namespace where the class VehicleType is declared in
  • miss a reference to the project where your VehicleType is declared in.

(or any combination of the above)


Some more words on the code example you provided

Let's assume that you have these classes:

public class VehicleType 
{
     ... some properties, constructors and methods
}

public class Car : VehicleType
{
     ... some properties, constructors and methods
}

Then you'd be able to create a factory class that produces new vehicles, something like

public static class VehicleFactory
{
    public static Vehicle CreateVehicle(...)
    {
        // conditional stuff that decides what kind of vehicle to construct
        if (...) 
        {
            return new Bicycle(...);
        }
        else if (...) 
        {
            return new Car(...);
        }
        else
        {
            throw new UnsupportedVehicleException();
        }
    }
}

Hope this helps you a bit on your way.

Solution 3

In C#, type information is commonly passed in one of two ways: an instance of the class, Type, or as generic type arguments. The latter affords you static type checking and constraints.

There are other strategies mentioned in other answers, but you may find them cumbersome and inappropriate.

Try this:

class Vehicle
{
    static ICollection<Vehicle> V;

    string Brand;
    string Model;
    int Year;
    int Price;

    static void AddNewVehicle<T>(string brand, string model, int year, int price)
        where T : Vehicle, new()
    {
        V.Add(new T() {
            Brand = brand,
            Model = model,
            Year = year,
            Price = price
        });
    }
}

Note this:

  • Vehicle has the fields: Brand, Model, Year, and Price
  • The generic argument on Vehicle.AddNewVehicle
  • If you want sub-classes of Vehicle to treat arguments differently, turn those fields into virtual/ abstract properties and override their set/ get behavior as desired.
Share:
10,197
kensing
Author by

kensing

Updated on June 04, 2022

Comments

  • kensing
    kensing almost 2 years

    Sorry, I may be lacking in terminology, but my searches haven't provided any answer despite the trivial question. Here goes -

    I have a superclass and wish to be able to create a new object of any of the subclasses with a method like the the following:

    static void AddNewVehicle(string brand, string model, int year, int price)
    {
        V.Add(new Car(brand, model, year, price));
    }
    

    I imagined that I would be able to do it like this:

    static void AddNewVehicle(object VehicleType, string brand, string model, int year, int price)
    {
        V.Add(new VehicleType(brand, model, year, price));
    }
    

    ...but I'm getting the following error:

    "The type or namespace name 'VehicleType' could not be found (are you missing a using directive or an assembly reference?)"