Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 542033
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T10:24:16+00:00 2026-05-13T10:24:16+00:00

I have a generic class that I need to constrain to only value types

  • 0

I have a generic class that I need to constrain to only value types (int, float, etc.). I have a method that calls the Parse method based on a test of the type. For example:

class MyClass<T>
{
    ...

    private static T ParseEntry(string entry)
    {
        if(typeof(T) == typeof(float))
        {
            return (T) float.Parse(entry);
        }

        if(typeof(T) == typeof(int))
        {
            .... you get the idea
        }
    }
}

Constraining T to struct doesn’t work and I really want to avoid boxing/unboxing if possible. Any ideas?

EDIT: To give a little more insight into this. I noticed in a library I’m developing that two classes had very similar properties/methods etc. the only difference was the underlying type of data (int or float). THis lead me to a design with generics. The only hangup is because of the call to the specific Parse method depending on if it’s a float or int. I could get around it with boxing/unboxing but I really wanted to avoid that if possible.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T10:24:17+00:00Added an answer on May 13, 2026 at 10:24 am

    Unfortunately, you cannot create constraints of the type of describe. You cannot write, for example:

    class MyClass<T> where T : int { ... } // won't compile
    

    You may be better off leaving the constraint to be struct, but add some runtime checks to make sure that T is only one of the supported types when you instantiate the class. Since you haven’t said much how you’re planning to use your class – it’s hard to offer alternative design advice on how to achieve better type safety.

    EDIT: You should look at the type converter option that Marc and others recommend. This seems like the way to go.

    EDIT: One possible idea that occurs to me, is to make the Parse() method actually be a delegate: Func<string,T> – that you assign during construction. This would make it possible for you to:

    1. Avoid the inefficient and awkward if/else logic.
    2. Improve the future use of your class to other value types (structs, BigDecimal, etc)

    Here’s a code example of what I mean:

    class MyClass<T>
    {
        private readonly Func<string,T> ParseEntry;
    
        public MyClass( Func<string,T> parser )    
        {
            ParseEntry = parser;
        }
    }
    
    public static class AvailableParsers
    {
        public static Func<string,int> ParseInt = s => int.Parse( s );
        public static Func<string,float> ParseFloat = s => float.Parse(s);
    }
    

    You can read about the available constraints here. The only constraints available are:

    • struct (optional)
    • new() (optional)
    • interface constraint (optional, multiple allows)
    • base class constraint (optional, only one allowed)
    • naked constraints ( such as where T : TResult )
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a generic class that should allow any type, primitive or otherwise. The
I have a generic class that I'm trying to implement implicit type casting for.
I have a generic class public MyClass<TContext, T> where TContext : DataContext that effectively
I have a class that has a Generic type G In my class model
I have a class that inherits a generic dictionary and an inteface public class
I have an abstract generic class BLL<T> where T : BusinessObject . I need
I have a generic class in C# with 2 constructors: public Houses(params T[] InitialiseElements)
I have a generic class in my project with derived classes. public class GenericClass<T>
I have a generic class, but I want my type to be forced to
I have a base class which is non-generic with a derived generic class. The

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.