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 6546927
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T11:46:04+00:00 2026-05-25T11:46:04+00:00

I have to build a special class behavior depending of the constructor’s argument. Say

  • 0

I have to build a special class behavior depending of the constructor’s argument. Say the Foo drawing should became forever green, if it was build(drawn) with a green pencil.
If any pencil where used, the Foo should be transparent…

Now, look at the code bellow. Is there a possibility to modify the “output” that the constructor “see” the real type of the passed in parameter object? (actually they are all “object”s):

class Program
{
    static void Main(string[] args)
    {
        object[] objs = { new IndexOutOfRangeException(), MyEnum.Beta, 45, new AssemblyName(), new { Name = "a" } };

        for (int i = 0; i < objs.Length; i++)
        {
            Console.WriteLine("{0} => {1} ", i, objs[i]);
        }
        Console.WriteLine("=========================== ");
        for (int i = 0; i < objs.Length; i++)
        {
            Foo myFoo = new Foo(objs[i]);
            Console.WriteLine("{0} => {1}", i, myFoo);
        }
    }
}

public class Foo
{
    object value;
    string typeName;

    public Foo(object obj)
    {
        value = obj;
        typeName = "object";
    }

    public Foo(MyEnum enm)
    {
        value = enm;
        typeName = "MyEnum";
    }

    public Foo(int myInt)
    {
        value = myInt;
        typeName = "int";
    }

    public Foo(Exception ex)
    {
        value = ex;
        typeName = "exception";
    }

    public override string ToString()
    {
        return string.Format("FOO (object = '{0}'; type = '{1}')", value, typeName);
    }
}

public enum MyEnum
{
    Alpha,
    Beta
}

OUTPUT

0 => System.IndexOutOfRangeException: Index was outside the bounds of the array.
1 => Beta
2 => 45
3 =>
4 => { Name = a }

===========================

0 => FOO (object = 'System.IndexOutOfRangeException: Index was outside the bound
s of the array.'; type = 'object')
1 => FOO (object = 'Beta'; type = 'object')
2 => FOO (object = '45'; type = 'object')
3 => FOO (object = ''; type = 'object')
4 => FOO (object = '{ Name = a }'; type = 'object')

EDIT:

As see some answers, I would like to stress that is not about the correct string to be displayed in the “type” variable, like using value.GetType(), but is about “entering” in the correct constructor is the question.

In other words, Why does the compiler not detect the correct type and “redirects” it to the correct constructor?

EDIT 2:

As mentioned by the answerers, the “way” to constructor is “built” at compile time, not in runtime. say a code like his

MyEnum en = MyEnum.Beta;
Console.WriteLine("Enum example: obj:{0} Foo:{1}", en, new Foo(en));

Will output the “good” output:

Enum example: obj:Beta Foo:FOO (object = 'Beta'; type = 'MyEnum')

so… apparently, any way to “bypass” this behavior but the runtime detection in constructor, like proposed Reed Copsey… ?!

  • 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-25T11:46:05+00:00Added an answer on May 25, 2026 at 11:46 am

    Why does the compiler not detect the correct type and “redirects” it to the correct constructor?

    This is because you’re passing in the object as a System.Object. (object[] objs = { n...) The constructor is chosen at compile time, not at runtime. The declaration of the variable used is seen by the compiler, and used to check for the appropriate type.

    As you mentioned in another comment:

    ok, what if I have a big array of objects, and don’t know, a priori their type?

    This is exactly why the compiler works this way. It can’t know, at compile time, which constructor you want, and since you have a System.Object constructor which works, it gets chosen.

    If you want to handle these specific types separately, but still construct the object as a System.Object, you’d have to add checks for that inside of the constructor for object and handle specific cases separately. This is not the most maintainable code, however, if you do that.

    public Foo(object obj)
    {
        value = obj;
        typeName = "object";
    
        // Change typeName if appropriate
        if (obj != null)
        {
            if (obj is MyEnum)
               typeName = "MyEnum";
            else if (obj is int)
               typeName = "int";
            else if (obj is Exception)
               typeName = "exception";
        }
    }
    

    Edit:

    Given that, in your real code, the constructor is likely going to do a lot more work, I would consider making a factory method to handle this. It would allow you to use a similar approach as above, but leave the type safe constructors in place:

    // I'd make the object constructor private, to prevent accidental usage:
    private Foo(object obj) { ...
    
    public static Foo CreateAppropriateFoo(object obj)
    {
         if (obj == null)
             return new Foo(obj); // Use object constructor
         else
         {            
            if (obj is MyEnum)
               return new Foo( (MyEnum)obj );
            else if (obj is int)
               return new Foo( (int)obj );
            else if (obj is Exception)
               return new Foo( (Exception)obj );
         }
    }
    

    This, at least, prevents the duplication of the constructor logic, as well as makes it a little more obvious that there is some logic happening at runtime.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have build a c# class library verification.dll using OpenCVSharp. This references OpenCvSharp.dll in
Say I have src/test/groovy/MyTest.groovy: class MyTest extends GroovyTestCase { void testDummy() { println 'DUMMY'
i have build a small function whose work to get value in alert box
I have build C# program that work with RAPI (communication to PPC or WinCE)
I have build a webapplication using ASP.NET MVC and JQuery. On my local machine
I have build my very first application to Android and I want now to
i have build a small test app in Flash Pro 5.5 overlayed with the
I have build a simple website with ASP.NET C#. It runs normally after I
We have build several web service based on .net. Now we want to create
For a client I have build a simple script that uploads multiple files(images), resizes

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.