Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use generic forms in C#?

Tags:

c#

.net

winforms

You should be able to create a generic form:

public partial class MyGenericForm<T> :     Form where T : class {     /* form code */     public List<T> TypedList { get; set; } } 

Is valid C#, and compiles. However the designer won't work and the form will throw a runtime exception if you have any images stating that it cannot find the resource.

I think this is because the windows forms designer assumes that the resources will be stored under the simple type's name.

like image 241
Keith Avatar asked Aug 14 '08 11:08

Keith


People also ask

What is generic in C?

Generics are syntax components of a programming language that can be reused for different types of objects. Typically, generics take the form classes or functions, which take type(s) as a parameter. Generics are also commonly referred to as templates , and in C++ are officially called templates.

Is generic type safe in C#?

Type Safety: Generic data types provide better type safety, especially in the case of collections. When using generics you need to define the type of objects to be passed to a collection. This helps the compiler to ensure that only those object types that are defined in the definition can be passed to the collection.

What is a generic class C?

Generic means the general form, not specific. In C#, generic means not specific to a particular data type. C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods, properties, events, delegates, and operators using the type parameter and without the specific data type.


1 Answers

Yes you can! Here's a blog post I made a while ago with the trick:

Designing Generic Forms

Edit: Looks like you're already doing it this way. This method works fine so I wouldn't consider it too hacky.

like image 110
Matt Hamilton Avatar answered Oct 09 '22 04:10

Matt Hamilton