tags:

views:

271

answers:

2

I want to Convert an int to a specific type and then return a string whose format depends on the type I converted it to.
I have a property that returns a Type object, and another that I want to return a string whose format depends on the Type.
Why doesn't the compiler like the code in HexString below?
Is there another equally brief way to do this?

public class TestClass
{
    private int value;
    public bool signed;
    public int nBytes;

    public int Value { get {return value;} set {this.value = value;}}

    public Type Type { 
        get { 
            switch (this.nBytes) {
            case 1:
                return (this.signed ? typeof(SByte) : typeof(Byte));
            case 2:
                return (this.signed ? typeof(Int16) : typeof(UInt16));
            default:
                return null;
            }
        }
    }

    public String HexString {
        get {
            //?? compiler error: "no overload for method 'ToString' takes '1' arguments
             return (Convert.ChangeType(this.Value, this.Type)).ToString("X" + this.nBytes);
        }
    }
}
+3  A: 

Try formatting the string via String.Format rather than using Object.ToString():

return String.Format("{0:x" + this.nBytes.ToString() + "}", 
    (Convert.ChangeType(this.Value, this.Type)));

Any type that implements a formattable ToString() method is not overriding System.Object.ToString() and as such you cannot call that method on an Object with parameters.

Andrew Hare
+1  A: 

ChangeType returns a System.Object. Unfortunately, only the numerical types provide a ToString overload with a format (string paramater). System.Object.ToString() takes no parameters.

Reed Copsey