Profile picture Schedule a Meeting
c a n d l a n d . n e t

Implied generic parameter types

Dusty Candland | |

I'm not sure of the exact name of this feature, but I stumbled across it today. If a generic method uses the type for a parameter, the complier assumes the generic type, which makes for cleaner code.

using System;

class Program
{
static void Main()
{
MyClass.WriteInputStatic("test");
MyClass obj = new MyClass();
obj.WriteInput(12);
}
}

public class MyClass
{
public static void WriteInputStatic<T>(T input) { Console.WriteLine(input); }
public void WriteInput<T>(T input) { Console.WriteLine(input); }
}

I can’t think of many use cases, but kind of a cool feature anyway. I was using it to serialize and deserialize a type for testing the correct serialization/deserialization.

internal static T Serialize<T>(T worker) where T : class
{
    MemoryStream serializationStream = new MemoryStream();
new BinaryFormatter().Serialize(serializationStream, worker);
byte[] bytes = serializationStream.ToArray();

MemoryStream deserializationStream = new MemoryStream(bytes);
object obj = new BinaryFormatter().Deserialize(deserializationStream);
return obj as T;
}

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: