<p><strong>Is there a way to enforce/limit the types that are passed to primitives?</strong> <em>(bool, int, string, etc.)</em></p>
<p>Now, I know you can limit the generic type parameter to a type or interface implementation via the <em>where</em> clause. However, this doesn't fit the bill for primitives (AFAIK) because they do not all have a common ground (apart from <em>object</em> before someone says! :P).</p>
<p>So, my current thoughts are to just grit my teeth and do a big <em>switch</em> statement and throw an <em>ArgumentException</em> on failure.</p>
<hr />
<p><strong>EDIT 1:</strong></p>
<p>Just to clarify:</p>
<p>The code definition should be like this:</p>
<pre><code>public class MyClass&lt;GenericType&gt; ....
</code></pre>
<p>And instantiation:</p>
<pre><code>MyClass&lt;bool&gt; = new MyClass&lt;bool&gt;(); // Legal
MyClass&lt;string&gt; = new MyClass&lt;string&gt;(); // Legal
MyClass&lt;DataSet&gt; = new MyClass&lt;DataSet&gt;(); // Illegal
MyClass&lt;RobsFunkyHat&gt; = new MyClass&lt;RobsFunkyHat&gt;(); // Illegal (but looks awesome!)
</code></pre>
<hr />
<p><strong>EDIT 2</strong></p>
<p>@Jon Limjap - Good point, and something I was already considering. I'm sure there is a generic method that can be used to determine if the type is of a value or reference type.</p>
<p>This could be useful in instantly removing a lot of the objects I don't want to deal with (but then you need to worry about the structs that are used such as <em>Size</em> ). Interesting problem no? :)</p>
<p>Here it is:</p>
<pre><code>where T: struct
</code></pre>
<p>Taken from <a href="http://msdn.microsoft.com/en-us/library/d5x73970.aspx" rel="nofollow noreferrer">MSDN</a>.</p>
<hr />
<p>I'm curious. Could this be done in .NET 3.x using extension methods? Create an interface, and implement the interface in the extension methods (which would probably be cleaner than a bit fat switch). Plus if you then need to later extend to any lightweight custom types, they can also implement the same interface, with no changes required to the base code.</p>
<p>What do you guys think?</p>
<p>The sad news is I am working in Framework 2!! :D</p>
<hr />
<p><strong>EDIT 3</strong></p>
<p>This was so simple following on from <a href="https://stackoverflow.com/questions/8941/generic-type-checking#8956">Jon Limjaps Pointer</a>.. So simple I almost want to cry, but it's great because the code works like a charm!</p>
<p>So here is what I did (you'll laugh!):</p>
<h2>Code added to the generic class</h2>
<pre><code>bool TypeValid()
{
    // Get the TypeCode from the Primitive Type
    TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType));

    // All of the TypeCode Enumeration refer Primitive Types
    // with the exception of Object and Empty (Null).
    // Since I am willing to allow Null Types (at this time)
    // all we need to check for is Object!
    switch (code)
    {
        case TypeCode.Object:
            return false;
        default:
            return true;
    }
}
</code></pre>
<p>Then a little utility method to check the type and throw an exception,</p>
<pre><code>private void EnforcePrimitiveType()
{
    if (!TypeValid())
        throw new InvalidOperationException(
            &quot;Unable to Instantiate SimpleMetadata based on the Generic Type of '&quot; + typeof(PrimitiveDataType).Name + 
            &quot;' - this Class is Designed to Work with Primitive Data Types Only.&quot;);
}
</code></pre>
<p>All that then needs to be done is to call <em>EnforcePrimitiveType()</em> in the classes constructors. Job done! :-)</p>
<p>The only downside, it only throws an exception at runtime (obviously) rather than design time. But that's no big deal and could be picked up with utilities like <a href="http://en.wikipedia.org/wiki/FxCop" rel="nofollow noreferrer">FxCop</a> (which we don't use at work).</p>
<p>Special thanks to Jon Limjap on this one!</p>

[{'answer_id': 8945, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 6, 'selected': False, 'text': '<pre><code>public class Class1&lt;GenericType&gt; where GenericType : struct\n{\n}\n</code></pre>\n\n<p>This one seemed to do the job..</p>\n'}, {'answer_id': 8954, 'author': 'JoshL', 'author_id': 630, 'author_profile': 'https://Stackoverflow.com/users/630', 'pm_score': 2, 'selected': False, 'text': '<p>Use a custom <a href="http://en.wikipedia.org/wiki/FxCop" rel="nofollow noreferrer">FxCop</a> rule that flags undesirable usage of <code>MyClass&lt;&gt;</code>.</p>\n'}, {'answer_id': 8956, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 6, 'selected': True, 'text': '<p>Primitives appear to be specified in the <a href="http://msdn.microsoft.com/en-us/library/system.typecode.aspx" rel="noreferrer"><code>TypeCode</code></a> enumeration:</p>\n\n<p>Perhaps there is a way to find out if an object contains the <code>TypeCode enum</code> without having to cast it to an specific object or call <code>GetType()</code> or <code>typeof()</code>?</p>\n\n<p><strong>Update</strong> It was right under my nose. The code sample there shows this:</p>\n\n<pre><code>static void WriteObjectInfo(object testObject)\n{\n    TypeCode    typeCode = Type.GetTypeCode( testObject.GetType() );\n\n    switch( typeCode )\n    {\n        case TypeCode.Boolean:\n            Console.WriteLine("Boolean: {0}", testObject);\n            break;\n\n        case TypeCode.Double:\n            Console.WriteLine("Double: {0}", testObject);\n            break;\n\n        default:\n            Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject);\n            break;\n        }\n    }\n}\n</code></pre>\n\n<p>It\'s still an ugly switch. But it\'s a good place to start!</p>\n'}, {'answer_id': 8980, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 5, 'selected': False, 'text': '<p>Pretty much what @Lars already said:</p>\n\n<pre><code>//Force T to be a value (primitive) type.\npublic class Class1&lt;T&gt; where T: struct\n\n//Force T to be a reference type.\npublic class Class1&lt;T&gt; where T: class\n\n//Force T to be a parameterless constructor.\npublic class Class1&lt;T&gt; where T: new()\n</code></pre>\n\n<p>All work in .NET 2, 3 and 3.5.</p>\n'}, {'answer_id': 69673, 'author': 'Doug McClean', 'author_id': 11173, 'author_profile': 'https://Stackoverflow.com/users/11173', 'pm_score': 2, 'selected': False, 'text': "<p>If you can tolerate using factory methods (instead of the constructors MyClass you asked for) you could always do something like this:</p>\n\n<pre><code>class MyClass&lt;T&gt;\n{\n  private readonly T _value;\n\n  private MyClass(T value) { _value = value; }\n\n  public static MyClass&lt;int&gt; FromInt32(int value) { return new MyClass&lt;int&gt;(value); }\n  public static MyClass&lt;string&gt; FromString(string value) { return new MyClass&lt;string&gt;(value); }\n  // etc for all the primitive types, or whatever other fixed set of types you are concerned about\n}\n</code></pre>\n\n<p>A problem here is that you would need to type <code>MyClass&lt;AnyTypeItDoesntMatter&gt;.FromInt32</code>, which is annoying. There isn't a very good way around this if you want to maintain the private-ness of the constructor, but here are a couple of workarounds:</p>\n\n<ul>\n<li>Create an abstract class <code>MyClass</code>. Make <code>MyClass&lt;T&gt;</code> inherit from <code>MyClass</code> <strong>and nest it within <code>MyClass</code></strong>. Move the static methods to <code>MyClass</code>. This will all the visibility work out, at the cost of having to access <code>MyClass&lt;T&gt;</code> as <code>MyClass.MyClass&lt;T&gt;</code>.</li>\n<li>Use <code>MyClass&lt;T&gt;</code> as given. Make a static class <code>MyClass</code> which calls the static methods in <code>MyClass&lt;T&gt;</code> using <code>MyClass&lt;AnyTypeItDoesntMatter&gt;</code> (probably using the appropriate type each time, just for giggles).</li>\n<li>(Easier, but certainly weird) Make an abstract type <code>MyClass</code> <strong>which inherits from <code>MyClass&lt;AnyTypeItDoesntMatter&gt;</code></strong>. (For concreteness, let's say <code>MyClass&lt;int&gt;</code>.) Because you can call static methods defined in a base class through the name of a derived class, you can now use <code>MyClass.FromString</code>.</li>\n</ul>\n\n<p>This gives you static checking at the expense of more writing.</p>\n\n<p>If you are happy with dynamic checking, I would use some variation on the TypeCode solution above.</p>\n"}, {'answer_id': 217079, 'author': 'Vivek', 'author_id': 7418, 'author_profile': 'https://Stackoverflow.com/users/7418', 'pm_score': 2, 'selected': False, 'text': '<p>You can simplify the <code>EnforcePrimitiveType</code> method by using <a href="http://msdn.microsoft.com/en-us/library/system.type.isprimitive.aspx" rel="nofollow noreferrer"><code>typeof(PrimitiveDataType).IsPrimitive</code></a> property. Am I missing something?</p>\n'}, {'answer_id': 686709, 'author': 'Matthew Boehlig', 'author_id': 83235, 'author_profile': 'https://Stackoverflow.com/users/83235', 'pm_score': 2, 'selected': False, 'text': "<p>@Rob, <code>Enum</code>'s will slip through the <code>TypeValid</code> function as it's <code>TypeCode</code> is <code>Integer</code>. I've updated the function to also check for <code>Enum</code>.</p>\n\n<pre><code>Private Function TypeValid() As Boolean\n    Dim g As Type = GetType(T)\n    Dim code As TypeCode = Type.GetTypeCode(g)\n\n    ' All of the TypeCode Enumeration refer Primitive Types\n    ' with the exception of Object and Empty (Nothing).\n    ' Note: must also catch Enum as its type is Integer.\n    Select Case code\n        Case TypeCode.Object\n            Return False\n        Case Else\n            ' Enum's TypeCode is Integer, so check BaseType\n            If g.BaseType Is GetType(System.Enum) Then\n                Return False\n            Else\n                Return True\n            End If\n    End Select\nEnd Function\n</code></pre>\n"}, {'answer_id': 11690199, 'author': 'gimlichael', 'author_id': 175073, 'author_profile': 'https://Stackoverflow.com/users/175073', 'pm_score': 2, 'selected': False, 'text': '<p>Having a similar challenge, I was wondering how you guys felt about the <a href="http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx" rel="nofollow">IConvertible interface</a>. It allows what the requester requires, and you can extend with your own implementations.</p>\n\n<p>Example:</p>\n\n<pre><code>    public class MyClass&lt;TKey&gt;\n    where TKey : IConvertible\n{\n    // class intentionally abbreviated\n}\n</code></pre>\n\n<p>I am thinking about this as a solution, all though many of the suggested was part of my selection also.</p>\n\n<p>My concern is - however - is it misleading for potential developers using your class?</p>\n\n<p>Cheers - and thanks.</p>\n'}, {'answer_id': 72332537, 'author': 'Chris Kao', 'author_id': 9823251, 'author_profile': 'https://Stackoverflow.com/users/9823251', 'pm_score': 0, 'selected': False, 'text': "<p>In dotnet 6, I encountered this error when using <code>struct</code>:</p>\n<blockquote>\n<p>The type 'string' must be a non-nullable value type in order to use it as parameter 'T'</p>\n</blockquote>\n<p>So I use IConvertible instead</p>\n<pre><code>var intClass = new PrimitivesOnly&lt;int&gt;();\nvar doubleClass = new PrimitivesOnly&lt;double&gt;();\nvar boolClass = new PrimitivesOnly&lt;bool&gt;();\nvar stringClass = new PrimitivesOnly&lt;string&gt;();\nvar myAwesomeClass = new PrimitivesOnly&lt;MyAwesomeClass&gt;(); // illegal\n\n// The line below encounter issue when using &quot;string&quot; type\n// class PrimitivesOnly&lt;T&gt; where T : struct\nclass PrimitivesOnly&lt;T&gt; where T : IConvertible\n{\n    \n}\n\nclass MyAwesomeClass\n{\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/8941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/832/']