Reputation: 95
I'm trying to create a substitute for kind of property, that accepts multiple types as inputs/outputs.
Here is some pseudo code of one ugly solution:
Basically i have piece of data and i need to be able assign multiple types to it, and react accordingly. I have pieces of data that i operate with, and i need efficient way to manage loading them from file names when needed, while maintaining the same code, if I'm manipulating with data, that's already loaded.
This would be awesome:
SomeDataClass data1 = new SomeDataClass();
SomeDataClass data2 = new SomeDataClass();
data1.Data = "somefile.dat";
data2.Data = data1.Data;
while SomeDataClass.Data is not type of string.
Upvotes: 2
Views: 580
Reputation: 2097
Not sure what the problem you're trying to solve with this really is, but it seems to me like you'd be better of with using a byte[], working with a stream of data, loaded either from disk or somewhere else.
Also consider just coding to a common Interface, instead of using dynamic and object.
Upvotes: 0
Reputation: 1063569
You can do much of that with an implicit conversion operator, i.e.
class SomeDataClass {
public SomeData Data {get;set;}
}
class SomeData {
static SomeData Load(string path) {
return new SomeData(); // TODO
}
public static implicit operator SomeData(string path)
{
return Load(path);
}
}
static class Program {
static void Main()
{
SomeDataClass data1 = new SomeDataClass();
SomeDataClass data2 = new SomeDataClass();
data1.Data = "somefile.dat"; // this is a load
data2.Data = data1.Data; // this is not a load
}
}
However! Frankly, I would consider it more desirable to just make the operation explicit:
class SomeDataClass {
public SomeData Data {get;set;}
}
class SomeData {
public static SomeData Load(string path) {
return new SomeData(); // TODO
}
}
static class Program {
static void Main()
{
SomeDataClass data1 = new SomeDataClass();
SomeDataClass data2 = new SomeDataClass();
data1.Data = SomeData.Load("somefile.dat");
data2.Data = data1.Data;
}
}
Upvotes: 0
Reputation: 65077
Have you considered using dynamic
?
class A {
public dynamic property1 { get; set; }
public dynamic property2 { get; set; }
}
class Program {
static void Main(string[] args) {
A a = new A();
A b = new A();
a.property1 = "hello world!";
b.property2 = a.property1;
Console.WriteLine(b.property2); // writes "hello world!"
}
}
Upvotes: 1