Hi, today I want to share with you innovative solution idea I want to make with Visual Studio 14 CTP that I found by looking to Roslyn project on CodePlex site. So what is the case here? Do you remember one of my last blog entry about Generic Free Pattern. That solution can make C# similar to JavaScript when you write the code but type-safe when the compiler uses it simultaneously. So what is the case of the third usage of our keyword? Let’s say we have a generic class with generic type argument T, and we have a constructor that needs an argument with type T. I would like to make something impossible right now, which is to make a generic constructor with “out T” as a generic argument. I have no better idea than transform that into Generic Free Pattern. Se let me start with a code sample that cannot be compiled… cannot be yet :).
namespace GenericFreeSandbox { using System; public interface IEntity { string Name { get; set; } } public class Entity: IEntity { public string Name { get; set; } } public class EntityManager<T> where T: IEntity { private readonly T entity; public EntityManager<out T>(T entity) { this.entity = entity; } public string GetName() { return entity.Name; } } public class EntityManagerTester { public static bool GetName() { var entity = new GenericFreeSandbox.Entity { Name = "Piotr Sowa's Entity for Roslyn Compiler Extension" }; var manager = new GenericFreeSandbox.EntityManager(entity); var name = manager.GetName(); return name == "Piotr Sowa's Entity for Roslyn Compiler Extension"; } } }
As you can see the innovation of above code is the “out T” generic argument for constructor for the EntityManager class. Please look at the EntityManagerTester class with the usage of this solution. Are you get it? I instantiated EntityManager with an entity without a generic parameter. I intended that EntityManager would figure out its generic type by modification from the Entity type given for the constructor. I will also show you an example of running this code to ensure it is valid. I like to invent new and different ways of testing code. So here it is.
namespace GenericFreeCompilerAndRunner { using System; class Program { static void Main(string[] args) { Console.WriteLine( "TEST EntityManagerTester.GetName() {0}", EntityManagerTester.GetName() == true ? "PASS" : "FAIL" ); } } }
I expect that the way of doing my solution will be SyntaxTree.ParseCompilationUnit(code) method to get syntax tree and then change/transform it to use Generic Free Pattern. I do not have a solution today, but I like to make it nice and share it with you. I hope you like this idea. One of the nice uses is for Dependency Injection solutions and framework classes that automatically figure out behavior by a given constructor argument. Without using Roslyn, C# code cannot be compiled. See you next time on CodingByToDesign.NET :).
p ;).