C# Non-generic method in generic class - c#

Am trying to define a class that provides a random number between two values. It shall work with ints as well as with floats.
To only have a single class, I'd like to use generics.
This works well for the member variables, but how do I define a method for only specific types?
The Random.Range method I use (from unity) can accept floats or ints so a cast is needed. The generic type does not seem to be castable at all however.
Have written this code to show what I am looking for. Does a syntax similar to this exist?
public class MinMaxSetting<T>
{
public T min;
public T max;
public MinMaxSetting(T min_val, T max_val)
{
min = min_val;
max = max_val;
}
public T GetRandom<int>()
{
return Random.Range((int)min, (int)max);
}
public T GetRandom<float>()
{
return Random.Range((float)min, (float)max);
}
}

Found a solution: Extension Methods!
Surely a bit quirky but it does what it's supposed to and it's readable.
public class MinMaxSetting<T>
{
public T min;
public T max;
public MinMaxSetting(T min_val, T max_val)
{
min = min_val;
max = max_val;
}
}
// Helper class just for the extension methods. The name is irrelevant.
public static class MinMaxSetting
{
public static float GetRandom(this MinMaxSetting<float> self)
{
return UnityEngine.Random.Range(self.min, self.max);
}
public static int GetRandom(this MinMaxSetting<int> self)
{
return UnityEngine.Random.Range(self.min, self.max);
}
}
Example:
public static void Main()
{
MinMaxSetting<float> my_setting = new MinMaxSetting<float>(5.3f, 20.4f);
Console.WriteLine(my_setting.GetRandom());
}

Related

Why is my method not being recognized by my generic object?

I've made a code that has an interface and an abstract class to make my main function to work with both objects. As I started to work around my function everything was working perfectly until I needed to get a function from the object itself.
My function is:
void addNode<T>(List<T> genericList) where T : IGraphs{
T genericNode = (T)Activator.CreateInstance(typeof(T));
genericNode.Number = contDirected;
if (genericList.Count > 0)
{
string connectedNode = "";
while (!connectedNode.Equals("0") && genericList.RemainingNodesExist(undirectedGraphs, genericNode))
{
}
}
}
}
Obviously the function is not yet finished but the problem is on my last "while". As I try to get the method "RemainingNodesExist", the IDE gives me an advice saying that List does not have a definition for the method. Im not sure why is that since I have it on my classes:
public interface IGraphs
{
public int Number { get; set; }
public List<int> LinkedNumbers { get; set; }
}
public abstract class AbstractGraphs<T>
{
public abstract bool RemainingNodesExist(List<T> list, T node);
}
And on the classes that inherit from those above:
public class DirectedGraph: AbstractGraphs<DirectedGraph>, IGraphs
{
public int Number { get; set; }
public List<int> LinkedNumbers { get; set; }
public DirectedGraph()
{
Number = Number;
LinkedNumbers = new List<int>();
}
public override bool RemainingNodesExist(List<DirectedGraph> list, DirectedGraph node)
{
int numbersConnected = node.LinkedNumbers.Count;
if (numbersConnected != list.Count)
{
return true;
}
return false;
}
public UndirectedGraph()
{
Number = Number;
LinkedNumbers = new List<int>();
}
public int Number { get; set; }
public List<int> LinkedNumbers { get; set; }
public override bool RemainingNodesExist(List<UndirectedGraph> list, UndirectedGraph node)
{
int numbersConnected = node.LinkedNumbers.Count;
if (numbersConnected != list.Count)
{
return true;
}
return false;
}
To better summarize whats my goal...
I have 2 objects that are exactly the same in properties, but the methods will probably be different in some situations. I used the generic class T because the program will use a list of objects not yet defined that can be any of the two objects mentioned above. What I want my program to do is run the "addNode" function and run the method of both objects based on their type.
Has anyone had to deal with a similar problem or could give me some direction on how to solve this?
I am very suspicious of this code base, it looks way way too complicated.
But to answer your specific question
while (!connectedNode.Equals("0") && genericList.RemainingNodesExist(undirectedGraphs, genericNode))
attempts to call a method on genericList, thats a List<XXX> passed as a parameter
That method (RemainingNodesExist) is defined here
public abstract class AbstractGraphs<T>
{
public abstract bool RemainingNodesExist(List<T> list, T node);
}
Its a method of a class called AbstractGraphs<T>
Which has no relation to List<AnythinG>
Its hard to say what you need to change because this is such a convoluted set of classes.
Maybe if you can explain why you think that method would be callable on a list that might make it clearer

Emulating F# `with` keyword in C#

Is there a way to emulate F#'s with keyword in C#? I know it will likely not be as elegant, but I'd like to know if there's any way to handle creating new immutable copies of data structures.
Records in F# are detailed here.
Here's an example of what I'm trying to do. We'll create "immutable" views of data via interfaces, while maintaining mutability in concrete classes. This lets us mutate locally (while working) and then return an immutable interface. This is what we're handling immutability in C#.
public interface IThing
{
double A { get; }
double B { get; }
}
public class Thing : IThing
{
double A { get; set; }
double B { get; set; }
}
However, when it comes time to make a change to the data, it's not very type (or mutability!) safe to cast it back and forth, and it's also a real pain to manually translate each property of the class into a new instance. What if we add a new one? Do I have to go track down each manipulation? I don't want to create future headache when I really only need what I had before, but with [some change].
Example:
// ...
IThing item = MethodThatDoesWork();
// Now I want to change it... how? This is ugly and error/change prone:
IThing changed = new Thing {
A = item.A,
B = 1.5
};
// ...
What are sound strategies for accomplishing this? What have you used in the past?
As there is no syntactic sugar I am aware of you'll have to either:
do it by hand (see below)
use some reflection/automapper (not a fan of this)
use some AOP techniques (neither a fan of those)
At least this is what I can think of right now.
I don't think the last two are a good idea because you bring on the big machinery to solve a very easy problem.
Yes when you have thousands of data-structures you might rethink this, but if you only have a couple of them I would not use it.
So what's left is basically smart-constructors and stuff like this - here is a simple example of how you could do it (note that you don't really need all of this - pick and choose) - it's basically missusing null/nullable to look for what you need - better options to this might be overloads or something like an Option<T> data-type but for now I think you get it:
class MyData
{
private readonly int _intField;
private readonly string _stringField;
public MyData(int intField, string stringField)
{
_intField = intField;
_stringField = stringField;
}
public MyData With(int? intValue = null, string stringValue = null)
{
return new MyData(
intValue ?? _intField,
stringValue ?? _stringField);
}
// should obviously be put into an extension-class of some sort
public static MyData With(/*this*/ MyData from, int? intValue = null, string stringValue = null)
{
return from.With(intValue, stringValue);
}
public int IntField
{
get { return _intField; }
}
public string StringField
{
get { return _stringField; }
}
}
To add to Carsten's correct answer, there's no way to do this in C# because it's not in the language. In F#, it's a language feature, where succinct record declaration syntax expands to quite a bit of IL. C# doesn't have that language feature (yet).
This is one of the reasons I no longer like to work in C#, because there's too much overhead compared to doing the same thing in F#. Still, sometimes I have to work in C# for one reason or the other, and when that happens, I bite the bullet and write the records by hand.
As an example, the entire AtomEventSource library is written in C#, but with immutable records. Here's an abbreviated example of the AtomLink class:
public class AtomLink : IXmlWritable
{
private readonly string rel;
private readonly Uri href;
public AtomLink(string rel, Uri href)
{
if (rel == null)
throw new ArgumentNullException("rel");
if (href == null)
throw new ArgumentNullException("href");
this.rel = rel;
this.href = href;
}
public string Rel
{
get { return this.rel; }
}
public Uri Href
{
get { return this.href; }
}
public AtomLink WithRel(string newRel)
{
return new AtomLink(newRel, this.href);
}
public AtomLink WithHref(Uri newHref)
{
return new AtomLink(this.rel, newHref);
}
public override bool Equals(object obj)
{
var other = obj as AtomLink;
if (other != null)
return object.Equals(this.rel, other.rel)
&& object.Equals(this.href, other.href);
return base.Equals(obj);
}
public override int GetHashCode()
{
return
this.Rel.GetHashCode() ^
this.Href.GetHashCode();
}
// Additional members removed for clarity.
}
Apart from the overhead of having to type all of this, it's also been bothering me that if you're doing (dogmatic) Test-Driven Development (which you don't have to), you'd want to test these methods as well.
Using tools like AutoFixture and SemanticComparison, though, you can make it somewhat declarative. Here's an example from AtomLinkTests:
[Theory, AutoAtomData]
public void WithRelReturnsCorrectResult(
AtomLink sut,
string newRel)
{
AtomLink actual = sut.WithRel(newRel);
var expected = sut.AsSource().OfLikeness<AtomLink>()
.With(x => x.Rel).EqualsWhen(
(s, d) => object.Equals(newRel, d.Rel));
expected.ShouldEqual(actual);
}
Here, it's still relatively verbose, but you can easily refactor this to a generic method, so that each test case becomes a one-liner.
It's still a bother, so even if you're writing most of your code in C#, you might consider defining your immutable types in a separate F# library. Viewed from C#, F# records look like 'normal' immutable classes like AtomLink above. Contrary to some other F# types like discriminated unions, F# records are perfectly consumable from C#.
Here is my attempt at emulating immutable mutations in C# via concrete classes. Some magic via generics, which includes type safety!
class Program
{
static void Main(string[] args)
{
var r = new Random();
// A new class item
IDataItem item = new DataItem
{
A = r.NextDouble(),
B = r.NextDouble(),
C = r.NextDouble(),
D = r.NextDouble()
};
// Type hinting here helps with inference
// The resulting `newItem` is an "immutable" copy of the source item
IDataItem newItem = item.With((DataItem x) =>
{
x.A = 0;
x.C = 2;
});
// This won't even compile because Bonkers doesn't implement IDataItem!
// No more casting madness and runtime errors!
IBonkers newItem2 = item.With((Bonkers x) => { /* ... */ });
}
}
// A generic record interface to support copying, equality, etc...
public interface IRecord<T> : ICloneable,
IComparable,
IComparable<T>,
IEquatable<T>
{
}
// Immutable while abstract
public interface IDataItem : IRecord<IDataItem>
{
double A { get; }
double B { get; }
double C { get; }
double D { get; }
}
// Mutable while concrete
public class DataItem : IDataItem
{
public double A { get; set; }
public double B { get; set; }
public double C { get; set; }
public double D { get; set; }
public object Clone()
{
// Obviously you'd want to be more explicit in some cases (internal reference types, etc...)
return this.MemberwiseClone();
}
public int CompareTo(object obj)
{
// Boilerplate...
throw new NotImplementedException();
}
public int CompareTo(IDataItem other)
{
// Boilerplate...
throw new NotImplementedException();
}
public bool Equals(IDataItem other)
{
// Boilerplate...
throw new NotImplementedException();
}
}
// Extension method(s) in a static class!
public static class Extensions
{
// Generic magic helps you accept an interface, but work with a concrete type
// Note how the concrete type must implement the provided interface! Type safety!
public static TInterface With<TInterface, TConcrete>(this TInterface item, Action<TConcrete> fn)
where TInterface : class, ICloneable
where TConcrete : class, TInterface
{
var n = (TInterface)item.Clone() as TConcrete;
fn(n);
return n;
}
}
// A sample interface to show type safety via generics
public interface IBonkers : IRecord<IBonkers> { }
// A sample class to show type safety via generics
public class Bonkers : IBonkers
{
public object Clone()
{
throw new NotImplementedException();
}
public int CompareTo(object obj)
{
throw new NotImplementedException();
}
public int CompareTo(IBonkers other)
{
throw new NotImplementedException();
}
public bool Equals(IBonkers other)
{
throw new NotImplementedException();
}
}

Creating a non-static version of compiler-based "dictionary" where keys are types

There is a very easy trick which creates a dictionary-like structure where keys are types.
The structure acts like a Dictionary<Type, T?> where keys are Type objects and values are instances of the corresponding types.
This wonderful structure is as fast as just a variable or array since the "lookup" is only done once by the compiler/JITter and the proper value reference is compiled into your program.
public static class MyDict<T> {
public static T Value { get; set; }
}
You can work with that structure like this:
MyDict<string>.Value = MyDict<int>.Value.ToString();
The problem is that this "dictionary" is global. The only way to create different dictionaries is to create different classes.
How can create a similar (fastest "lookup", no boxing) non-static structure? (Without code generation.)
Simply said: I want to have multiple Dictionary<Type, object>-like objects without lookup costs, casting and boxing.
Here's an approach that extends the method described in the question:
public class TypeDict
{
public T Get<T>()
{
return MyDict<T>.Values[this];
}
public void Set<T>(T value)
{
MyDict<T>.Values[this] = value;
}
private static class MyDict<T>
{
public static Dictionary<TypeDict, T> Values { get; private set; }
static MyDict()
{
Values = new Dictionary<TypeDict, T>();
}
}
}
Now we can use the TypeDict like this:
void X()
{
var a = new TypeDict();
var b = new TypeDict();
a.Set<int>(1);
a.Set<double>(3.14);
a.Set("Hello, world!");
//Note that type inference allows us to omit the type argument
b.Set(10);
b.Set(31.4);
b.Set("Hello, world, times ten!");
Console.WriteLine(a.Get<int>());
Console.WriteLine(a.Get<double>());
Console.WriteLine(a.Get<string>());
Console.WriteLine();
Console.WriteLine(b.Get<int>());
Console.WriteLine(b.Get<double>());
Console.WriteLine(b.Get<string>());
}
Ark-kun is using generics to essentially generate unique types at compile time. With a generic type, any static members are unique to that specific closed generic type. This way it's processed as fast as a standard static member lookup.
The above usage is equivalent to something like this:
public static class MyDict_String
{
public static string Value { get; set; }
}
public static class MyDict_Int32
{
public static int Value { get; set; }
}
MyDict_String.Value = MyDict_Int32.Value.ToString();
AFAIK, types are "static" (in that you can't define more than one that way) so I don't know of a way to cheat around this and maintain the same performance of a statically compiled member lookup.
Your best bet otherwise (I think) is to create a generic instance type that wraps its own dictionary that uses System.Type for its keys and System.Object for its values to which you have to perform boxing/casting when inserting/retrieving values.
EDIT: Here's a simple implementation wrapping a dictionary:
public class MyTypedDict
{
private Dictionary<Type, object> Values = new Dictionary<Type, object>();
public T Get<T>()
{
object untypedValue;
if (Values.TryGetValue(typeof(T), out untypedValue))
return (T)untypedValue;
return default(T);
}
public void Set<T>(T value)
{
Values[typeof(T)] = value;
}
}
Thinking about it more, it might be possible to achieve a more property-like syntax using an ExpandoObject (http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx) through some tomfoolery, but I feel like this would be pretty abusive and I can only assume terribly prone to runtime errors. (plus it would afford you nothing at compile time)
EDITx2: If you really want to have different sets of values, you could nest it within another generic type:
public static class ValueSets<T>
{
public static class MyDict<U>
{
public static U Value { get; set; }
}
}
With usage like:
ValueSets<int>.MyDict<string>.Value = "Hello ";
ValueSets<bool>.MyDict<string>.Value = "World!";
string helloworld = ValueSets<int>.MyDict<string>.Value + ValueSets<bool>.MyDict<string>.Value;
Console.WriteLine(helloworld);//Hello World!
But then the initial type int and bool in this case become "magical" and without meaning, plus you would need to provide a unique type per distinct set of values you'd like to use. Plus you could not pass it around and modify as an instance variable, rather it'd be statically accessible (so long as you have access to use the type T). So perhaps you could declare minimally visible types that are named with meaning and use those:
internal class MyFirstWords {}
internal class MySecondWords {}
ValueSets<MyFirstWords>.MyDict<string>.Value = "Hello ";
ValueSets<MySecondWords>.MyDict<string>.Value = "World!";
string helloworld = ValueSets<MyFirstWords>.MyDict<string>.Value + ValueSets<MySecondWords>.MyDict<string>.Value;
Console.WriteLine(helloworld);//Hello World!
Regardless, I think this is quite wacky and I wouldn't recommend it.
A more complicated version. Don't know if it's closer:
Define a generic dictionary:
public class MyDictionary<T>
{
Dictionary<string, T> dict;
public MyDictionary()
{
dict = new Dictionary<string, T>();
}
public T this[string name]
{
get
{
if (dict.ContainsKey(name))
return dict[name];
else
return default(T);//or throw
}
set
{
dict[name] = value;
}
}
}
Then a repository to store those dictionaries:
public class MyRepository
{
List<object> repo;
public MyRepository()
{
repo = new List<object>();
}
public void Add<T>(string name, T value)
{
if (!repo.OfType<MyDictionary<T>>().Any())
repo.Add(new MyDictionary<T>());
var dict = repo.OfType<MyDictionary<T>>().FirstOrDefault();
dict[name] = value;
}
public T GetValue<T>(string name)
{
if (!repo.OfType<MyDictionary<T>>().Any())
return default(T);//or throw
else
{
var dict = repo.OfType<MyDictionary<T>>().FirstOrDefault();
return dict[name];
}
}
}
And finally you may use this repository:
MyRepository repo = new MyRepository();
repo.Add("A", 1);
repo.Add("B", 1);
int i = repo.GetValue<int>("A") + repo.GetValue<int>("B");
In this example, there is MyDictionary<T> boxing to object is left.
From the other side, if your are working with some certain types you may not use thie repository class at all. But utilize separate dictionaties.
MyDictionary<int> intDict = new MyDictionary<int>();
intDict["A"] = 1;
intDict["B"] = 2;
int i = intDict["A"] + intDict["B"];
However it's the same as working with
Dictionary<string, int> intDict = new Dictionary<string, int>();
So the MyRepository class may be edited to use Dictionary<string, T> instead of MyDictionary<T>.
#Konstantin's answer made me remember that there is actually a very fast lookup method - array indexing. This crude PoC code shows a variant of the required structure.
public class TypeDictionary {
static int _maxId = 0;
int _id;
static class Store<T>{
internal static List<T> Values = new List<T>();
}
public TypeDictionary() {
_id = _maxId++;
}
public T GetValue<T>() {
return Store<T>.Values[_id];
}
public void SetValue<T>(T value) {
while(Store<T>.Values.Count < _id) {
Store<T>.Values.Add(default(T));
}
Store<T>.Values[_id] = value;
}
}
This code can be used as follows:
var dict1 = new TypeDictionary();
dict1.SetValue("my string");
string result = dict1.GetValue<string>();
The problem with this solution is it's memory usage caused by the repository being not sparse. This also makes first time value setting more expensive.
Try this:
public class MyDictionary
{
List<object> values;
public MyDictionary()
{
values = new List<object>();
}
public T GetValue<T>()
{
return values.OfType<T>().FirstOrDefault();
}
public bool Add<T>(T value)
{
if (values.OfType<T>().Any())
return false;
else
{
values.Add(value);
return true;
}
}
}
and use it:
var md = new MyDictionary();
md.Add("!!!");
string s = md.GetValue<string>();
This class may store up to one value of type T. But there could corner cases with derived classes and interfaces I guess. You may check, if it suits your need, and probably modify it as you need, if it's close to what you need in general.
What you are looking for is impossible in C#. The language does not support a container that could store multiple objects of different types yet provides a look up method that does not involve casting, boxing or unboxing. You could accomplish something like this with macros in C++, or via a language like javascript where the structure of types can be changed at run-time.
The usage case you are describing fits quite closely with the purpose for which ConditionalWeakTable<TKey,TValue> was added to .NET 4.0. For the purpose you describe, you would include such a table in a static generic class, and then for every class object that's supposed to contain a reference to an item of a particular type you would store into that type's table a reference to object that's supposed to contain the item along with either a reference to the item, or else a reference to a simple item-holder object (note that entries in ConditionalWeakTable will evaporate when an object ceases to exist, but are otherwise immutable, so if you want a mutable association you'll need to create an object to hold it).
Building on #phoog's example with #supercat's suggestion
public class TypeDict
{
public T Get<T>() where T : class
{
T value;
InnerDict<T>.Values.TryGetValue(this, out value);
return value;
}
public void Set<T>(T value) where T : class
{
var cwt = InnerDict<T>.Values;
// lock+remove+add https://github.com/dotnet/coreclr/issues/4545
lock (cwt)
{
cwt.Remove(this);
cwt.Add(this, value);
}
}
private static class InnerDict<T> where T : class
{
public static ConditionalWeakTable<TypeDict, T> Values { get; private set; }
static InnerDict()
{
Values = new ConditionalWeakTable<TypeDict, T>();
}
}
}

Read property from the same class

In C# if I have this in a class:
public int SomeNumber
{
get { return 6; }
}
How can I read (get) that number from a function in the same class if the function receives a variable with the same name? Example:
public bool SomeFunction(int SomeNumber)
{
check if SomeNumber (the one passed to this function) == SomeNumber (the one from the public int)
}
You would simply invoke the property get in the method:
public void MyMethod()
{
var someNum = SomeNumber; // basically, var somNum = this.SomeNumber;
}
EDIT: To clarify with OP's edit:
public void MyMethod(int someNumber)
// Change the naming of your parameter so it doesnt clash with the property
{
if(someNumber == SomeNumber)
// Do Stuff
}
Same as if it were a field:
public void SomeOtherFunction()
{
var x = SomeNumber;
}
Although the other suggestions do work well (and adhere to easier to read/maintain code), they don't directly answer your question. Given a class
public class SomeClass
{
public int SomeNumber { get { return 6; } }
...
And a function with a parameter passed in
public void SomeMethod(int SomeNumber)
{
// Your code here...
You can access the passed in parameter and property like so:
if (SomeNumber > this.SomeNumber)
{
// Your results here
The distinction is that if you refer to just the variable name, it will use the variable from the same scope, i.e. the passed in variable. If you specify use "this." then you always get the class member.
Note: This does not work with Static classes, as there is no instance of the class. (Can't use "this.whatever") and you will be stuck. There are many coding Standards out there and some of them states that it is best practice to use the form "myVariable" for method parameters, "MyVariable" for property names, and _myVariable for property backing stores, to easily distinguish between them in your code.
public class FavoriteNumber
{
public int SomeNumber
{
get { return 6; }
}
Public int Twelve()
{
return SomeNumber*2;
}
}
Please run this code and you will get it.. Use this operator to refer the class level variale.
public void CheckNumber(int SomeNumber)
{
Console.WriteLine(SomeNumber);
Console.WriteLine(this.SomeNumber);
}

Referring to attributes in generic types?

I'm teaching myself C#, so forgive me if this seems slightly obvious.
I'm trying to write a generic function that I can pass an array of structs into and then use one of the attributes of the struct. I have no idea how to declare a generic datatype in a function in a way that I can refer to attributes in the way needed.
Maybe what I'm asking can be better communicated in code - this is a non-working function to illustrate what I'm trying to do, how it strikes me as logical that it should work without actually knowing how to write it:
public static int AFunctionIsThis<DataType, int DataType.Value>(DataType passedrecord)
{
temp = passedrecord.Value * 2 + 1;
return temp;
}
And I want to be able to call it normally while specifying the attribute of the struct to be passed.
int NewVariable = AFunctionIsThis<ThisIsAStruct, ThisIsAStruct.AnIntAttribute>(ThisIsADeclaredStruct);
Thankyou very much,
Hanii Puppy.
You can't specify members that a generic type should contain, you can only specify the generic data type.
You would use an interface where the property is defined:
public interface IHaveValue {
int Value { get; }
}
Your struct would then implement the interface, and you can specify the interface as the generic data type:
public static int AFunctionIsThis<T>(T passedrecord) where T : IHaveValue {
return passedrecord.Value * 2 + 1;
}
However, with what you are using it for, you don't need to use generics at all, you can just use the interface:
public static int AFunctionIsThis(IHaveValue passedrecord) {
return passedrecord.Value * 2 + 1;
}
Note that you should most likely not use a struct at all, but a class. A struct is more complicated to implement correctly, so you should stick to classes until you have a really good reason to use a struct.
(To start with, note that the word "attribute" has a different meaning in .NET from the OOP sense.)
Use a Converter<T,int> and Action<T,int> delegate to get and set the member, respectively.
e.g.
public static int AFunctionIsThis<DataType>(DataType passedrecord, Converter<DataType,int> getter)
{
temp = getter(passedrecord) * 2 + 1;
return temp;
}
and then call it
AFunctionIsThis(ThisIsADeclaredStruct, x => x.AnIntProperty);
If you also need to set the value, you can use
AFunctionIsThis(ThisIsADeclaredStruct, x => x.AnIntProperty, (x, v) => { x.AnIntProperty = v; });
or do some magic with Expression<Converter<T>> to yank out the member reference and create a matching setter.
Hanii Puppy:
In short, yes, you should be able to do what you are doing, but here is a syntax that works:
public static int AFunctionIsThis<T>(T passedRecord) where T : DataType
{
var temp = passedRecord.Value;
return temp;
}
public class DataType
{
public int Value { get; set; }
}
Hope that helps.
Dave
What you want to do, is define a generic method that accepts only T that implements a certain interface or is derived from certain base class that has an int member called Value.
e.g:
public interface IClass { int Value{get;set;} }
public class ExampleImpl : IClass
{
int Value{get;set;}
/* Additional Members\methods here */
}
public class HelperClass
{
public static int GenMethod<T>(T item) where T:IClass
{
return item.Value * 2 + 1;
}
}

Categories