Sergio0694
Sergio0694

Reputation: 4577

How to instantiate a class and assign a value as with standard types

Let's say I have a class like this:

public class MyCustomObject
{
    //For Type I mean int, String, or any other Type I might want to use
    private Type variable;

    public int someRandomMethod() { /* ... */ }
}

Is there a way to instantiate it with a simple declaration and assignment, like

MyCustomObject test = 20; //If I had int as my variable type

Just like:

String check1 = "Here I'm creating a new String";
Int32 myNumber = 42;

I mean, is it possible to do it?

Do I have to implement a specific interface or anything else in my class to do that?

Or, if I have a class like this:

public class MyCustomList
{
    private List<MyCustomObject>;

    public int someRandomMethod() { /* ... */ }
}

To instantiate it with something like:

MyCustomList myList = new List<MyCustomObject>() { 7, 25, 42 };

This probabily won't make any sense, but I don't think I'm the first one to think about something like this :D

Thanks for your help!

Sergio

Upvotes: 0

Views: 83

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101711

Yes there is a way.You can declare implicit conversions from any type to your type.For example:

public static implicit operator MyCustomObject(int x)
{
    return new  MyCustomObject { SomeProperty  = x };
}

So it's not something specific to built-in types.But this is not an ideal way either.You should use it when it's necessary and makes sense. If you wanna write less code when initializing objects use constructors or object initializers.

Upvotes: 3

Related Questions