Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Property in C# [duplicate]

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!

like image 983
rachmos Avatar asked Apr 06 '10 18:04

rachmos


People also ask

Which is a generic property?

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.

What are generics in C?

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.

What is generic type?

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.

What is generic method in C#?

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.


1 Answers

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; 
like image 51
Fredrik Mörk Avatar answered Sep 29 '22 20:09

Fredrik Mörk