REG GENERIC METHOD - c#

I had a thought on using the generic method in c# as like we do in c++.
Normally a method looks like this:
public static (void/int/string) methodname((datatype) partameter)
{
return ...;
}
I had a thought whether can we implement the generics to this method like this:
public static <T> methodname(<T> partameter)
{
return ...;
}
Using as a generic to define the datatype.
Can anyone pls suggest whether the above declaration is correct and can be used in c#?
Thanks in advance.

Not quite like that, no. It would be:
public static T MethodName<T>(T parameter)
{
...
}
The <T> after MethodName shows that it's introducing a type parameter.
EDIT: As per the comment, you can't use this for a void method - you can't use void as a type argument, basically.

Related

Default values for method optional attributes

I have a method:
public void MyMethod(string myParam1,string myParam2="")
{
myParam2 = (myParam2 == "")?myParam1:myParam2;
}
Is there any way to do this something like:
public void MyMethod(string myParam1,string myParam2 = (myParam2 == "")?myParam1:myParam2)
No.
The default value of parameters needs to be known at compile time. The first snippet you provided is the correct way to do this. Or as has been pointed out by other answers, provide an overload method that only accepts a single parameter.
In order to perform what you want you'll need to use an overload instead of an optional parameter.
There is no chance I believe what you tried to.
If you want to do process like this, best options looks like method overloading.
Overload resolution is a compile-time mechanism for selecting the best
function member to invoke given an argument list and a set of
candidate function members.
Not directly, as the default value must be known at compile time. The first method you describe is the correct way to do this.
However, you could do:
Set a default of null and coalesce it as you use it:
public void MyMethod(string myParam1, string myParam2 = null)
{
Console.WriteLine(myParam2 ?? myParam1);
}
Use overloading:
public void MyMethod(string myParam1, string myParam2)
{
Console.WriteLine(myParam2);
}
public void MyMethod(string myParam1)
{
MyMethod(myParam1, myParam1);
}

How to access static methods of generic types

public class BusinessObjects<O>
where O : BusinessObject
{
void SomeMethod()
{
var s = O.MyStaticMethod(); // <- How to do this?
}
}
public class BusinessObject
{
public static string MyStaticMethod()
{
return "blah";
}
}
Is there a correct object oriented approach to accomplishing this or will I need to resort to reflection?
EDIT: I went too far in trying to oversimplify this for the question and left out an important point. MyStaticMethod uses reflection and needs the derived type to return the correct results. However, I just realized another flaw in my design which is that I can't have a static virtual method and I think that's what I would need.
Looks like I need to find another approach to this problem altogether.
You can't access a static method through a generic type parameter even if it's constrained to a type. Just use the constrained class directly
var s = BusinessObject.MyStaticMethod();
Note: If you're looking to call the static method based on the instantiated type of O that's not possible without reflection. Generics in .Net statically bind to methods at compile time (unlike say C++ which binds at instantiation time). Since there is no way to bind statically to a static method on the instantiated type, this is just not possible. Virtual methods are a bit different because you can statically bind to a virtual method and then let dynamic dispatch call the correct method on the instantiated type.
The reason you can't reference the static member like this:
O.MyStaticMethod();
Is because you don't know what type O is. Yes, it inherits from BusinessObject, but static members are not inherited between types, so you can only reference MyStaticMethod from BusinessObject.
If you are forcing O to inherit from BusinessObject, why not just call it like this:
void SomeMethod()
{
var s = BusinessObject.MyStaticMethod(); // <- How to do this?
}

Referencing a function in a variable?

Say I have a function. I wish to add a reference to this function in a variable.
So I could call the function 'foo(bool foobar)' from a variable 'bar', as if it was a function. EG. 'bar(foobar)'.
How?
It sounds like you want to save a Func to a variable for later use. Take a look at the examples here:
using System;
public class GenericFunc
{
public static void Main()
{
// Instantiate delegate to reference UppercaseString method
Func<string, string> convertMethod = UppercaseString;
string name = "Dakota";
// Use delegate instance to call UppercaseString method
Console.WriteLine(convertMethod(name));
}
private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}
}
See how the method UppercaseString is saved to a variable called convertMethod which can then later be called: convertMethod(name).
Using delegates
void Foo(bool foobar)
{
/* method implementation */
}
using Action delegate
Public Action<bool> Bar;
Bar = Foo;
Call the function;
bool foobar = true;
Bar(foobar);
Are you looking for Delegates?
You need to know the signature of the function, and create a delegate.
There are ready-made delegates for functions that return a value and for functions that have a void return type. Both of the previous links point to generic types that can take up to 15 or so type arguments (thus can serve for functions taking up to that many arguments).
If you intend to use references to functions in a scope larger than a local scope, you can consider defining your own custom delegates. But most of the time, Action and Func do very nicely.
Update:
Take a look at this question regarding the choice between defining your own delegates or not.

Type-ing: how to pass the type?

I have a few tables in my database and they all contain a different inherited type of a DataRow.
In addition I have a class that is supposed to handle some things in my DataGrid
(My database Tables are connected to DataGrids).
In order to do that, one of the methods in this DataGrid handler has to cast the rows to the exact inherited type of a DataRow.
something like this:
(TempDataRow as DataRowTypeThatInheritsFromRegularDataRow).SpecialParameter = something;
In order to do that, I have to pass the method the inherited DataRow type, so it will know how to do the casting.
The method will generally look like this:
public void DoSomething(DataRowType Type)
{
(TempDataRow as Type).SpecialParameter = something;
}
How to pass the type?
Regular 'Type' type does not compile.
and if I pass just 'DataRow' it won't know how to do the casting.
If you are using C# 4.0, then have you considered the use of the 'dynamic' type?
dynamic row = getDataRow();
doSomething( row );
public void doSomething( DataRowTypeThatInheritsFromRegularDataRow row )
{
// <insert code here>
}
public void doSomething( SomeOtherDataRowType row )
{
// <insert code here>
}
This example should choose at run-time which function to call, based upon what getDataRow() actually returns.
For further reading of dynaminc see msdn
There are a number of ways you could do this.
First, you could find a common base class or interface that all types share, and then have DoSomething() take that base class or interface, or if you want to be totally dynamic, you could use reflection. It's hard to tell you how to do it, because you haven't given any concrete example:
using System.Reflection;
...
public void DoSomething(object foo) {
var dataType = foo.GetType();
type.GetProperty("SomeDynamicName").SetValue(foo, someOtherValue);
}
(though if you were using C# 4.0, as TK points out, you could just use the dynamic type and be done with it!)
You could use:
TempDataRow as Type.GetType("DataRowTypeName")

Passing in <T> to a method where GetEnum<T> is called

I’m using an API that has an object that returns IEnumerable<T>, so something like Object.GetEnum<T>.
I have a method that within it will call GetEnum but I want to add to the method’s parameters the ability to pass the parameter type. So for example I want to do:
private void myMethod(apiClass??? apiclass)
{
IEnumerable< itemType > enumX = ObjectGetEnum< itemType >
}
private void Main()
{
myMethod(apiClass1);
myMethod(apiClass2);
}
So as above I don’t know what the parameter type should be in myMethod or how to write the code that gets the enumerator. I tried passing “apiClass”, the class which apiClass1 and apiClass2 inherit from. But then got stuck there on what to do…and I don’t think that really work anyways.
So I’m not sure if I just don’t know how in C# to do this, or if it is even possible, …. or perhaps I’m missing something in the API (or the API is missing something to facilitate this).
Thanks
FKC
Okay, I'm going to take a stab at this, although I'd like the question to be clarified. I suspect you just need to make the method generic:
private void MyMethod<TItem>() where TItem : ApiClass
{
IEnumerable<TItem> enumX = ObjectGetEnum<TItem>();
}
private static void Main()
{
MyMethod<ApiClass1>();
MyMethod<ApiClass2>();
}
Are you trying to access the type parameter of the closed constructed type inside a method? Maybe something like this will work:
using System;
class Foo<T> { }
class Program
{
static void Main()
{
myMethod(new Foo<String>());
}
private static void myMethod<T>(Foo<T> foo)
{
// use the T parameter in here
}
}
You need something like this:
private void myMethod<T>()
{
IEnumerable<T> enumX = ObjectGetEnum<T>();
}

Categories

Resources