Reputation: 141
I am not sure if this can be accomplished at all but here is my question.
Using C#, is it possible to declare a generic or non-typed variable but later in my code specify what that variable should be?
object genericObject;
if (!testFlag)
{
genericObject = new SpecificObject1();
}
if (testFlag)
{
genericObject = new SpecificObject2();
}
genericObject.FirstName = "Samuel";
genericObject.LastName = "Jackson";
I am hoping that after the "if logic" I can now call the similar methods each "specific" object had in common.
So is it possible to create some form of generic object in the beginning of my code and instantiate the specific object I want to use later?
Maybe there is a design pattern or refactoring effort that needs to be considered here as well.
Upvotes: 0
Views: 116
Reputation: 148980
I'd recommend you define a custom interface that encapsulates all the members you need to use, and implement it on both of your concrete types::
interface IMyInteface
{
string FirstName { get; set; }
string LastName { get; set; }
}
class SpecificObject1 : IMyInterface { ... }
class SpecificObject2 : IMyInterface { ... }
And then declare your variable to be an instance of that interface:
IMyInterface genericObject;
if (!testFlag)
{
genericObject = new SpecificObject1();
}
if (testFlag)
{
genericObject = new SpecificObject2();
}
genericObject.FirstName = "Samuel";
genericObject.LastName = "Jackson";
But if that's not an option, you could use dynamic
, which will force any members to be evaluated at run time:
dynamic genericObject;
if (!testFlag)
{
genericObject = new SpecificObject1();
}
if (testFlag)
{
genericObject = new SpecificObject2();
}
genericObject.FirstName = "Samuel";
genericObject.LastName = "Jackson";
Upvotes: 0
Reputation: 62248
If your types, you are going to assign later, are completely unrelated to each other and mainly have different set of methods to execute, dynamic could be your choice of preference in this case.
In other cases, use standard OOP
techniques, like inheritance and polymorphism to achieve what you are talking about.
Upvotes: 0
Reputation: 245389
If both SpecificObject1
and SpecificObject2
share similar properties, you could add an interface for them. You could then declare genericObject
as the interface type and assign the concrete type later:
public interface SomeInterface
{
string FirstName { get; set; }
string LastName { get; set; }
}
public class SpecificObject1 : SomeInterface
{
// Implementation Details
}
public class SpecificObject2 : SomeInterface
{
// Other Implementation Details
}
You would then be able to use them in the following manner:
SomeInterface genericObject;
genericObject = testFlag ? new SpecificObject2() : new SpecificObject1();
Upvotes: 1
Reputation: 887195
You need to move all of the common members to a common base class or interface, then declare the variable as that type.
Upvotes: 0