Possible Duplicate:
Making a generic property
I'm not quite sure how to do that, but what I would like to do is to create a special type of property that will perform specific tasks at the get
and set
, and will be defined on generic type. For example, when writing this:
MyProp<String> name;
a pre-defined get
and set
will be performed on the string value.
How can that be done?
Thanks!
In topology and algebraic geometry, a generic property is one that holds on a dense open set, or more generally on a residual set, with the dual concept being a nowhere dense set, or more generally a meagre set.
Generics is a technique that enriches your programs in the following ways − It helps you to maximize code reuse, type safety, and performance. You can create generic collection classes. The . NET Framework class library contains several new generic collection classes in the System.
A generic type is a generic class or interface that is parameterized over types. The following Box class will be modified to demonstrate the concept.
A generic method is a method that is declared with type parameters, as follows: C# Copy. static void Swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } The following code example shows one way to call the method by using int for the type argument: C# Copy.
You can make a generic class like this:
public class MyProp<T> { private T _value; public T Value { get { // insert desired logic here return _value; } set { // insert desired logic here _value = value; } } public static implicit operator T(MyProp<T> value) { return value.Value; } public static implicit operator MyProp<T>(T value) { return new MyProp<T> { Value = value }; } }
...then use it in a class like so:
class SomeClass { public MyProp<int> SomeProperty { get; set; } }
The implicit operators means that you do not need to explicitly set or get the Value
property of MyProp
, but can write code to access the value in a more "natural" way:
SomeClass instance = new SomeClass(); instance.SomeProperty = 32; int someInt = instance.SomeProperty;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With