C# A problem with return T - c#

I have a method that converts a number from string to the T, e.g int
public static T GetItemIdFromUrl<T>(string itemName)
{
try
{
...
int ad_id = int.Parse(stringNumber);
return (T)(object)ad_id;
}
catch
{
return (T)(object)-1;
}
}
but as a result I have a hex code 0xffffffa5 instead of 91. Why ?

Well, it's hard to know for sure why it's returning 0xffffffa5 without knowing the input string, but your code is going to throw an exception if T is anything other than either int or a enum with an underlying base type of int. For example, it will throw if T is double. Your method isn't really generic - the value it's trying to return is always an int. Why is your method not just declared to return int? If you want to convert from int to some other type (double, long, whatever) just let that conversion be done on assignment. The unboxing conversion in your code will not work unless T is int or an appropriate enum (the latter of which seems unlikely).
One thing to note is that 0xffffffa5 is the bit pattern for -91. Is it possible that you've only seen that result in the debugger, and the result is meant to be -91 rather than 91?

Even if your intention is to genericize the handling of different numeric types (e.g., double, decimal, etc.), this isn't the way to do it. When you box to object, and then unbox to T, it will only work if the boxed type actually is T. In other words, it will not perform a type conversion for you.
The only way (that I know of) to do the type conversion from object to whatever you want is by using the Convert class:
return (T)Convert.ChangeType(ad_id, typeof(T));
Even this is fragile, obviously (as it won't work if T is any non-numeric type); but at least it won't throw exceptions in pretty much all cases you're trying to cover. (Your method as it is currently implemented will throw for every T except int.)

I think you have a fundamental misunderstanding of what generics are and how they're supposed to be used. The whole point of generics is to have the benefit of working on different types while not losing type safety which is what happens when you cast to object
That being said Jon Skeet is probably correct that it's probably the way the debugger is displaying the result.

I think you are doing something else where you show the ellipses (...):
try
{
...
int ad_id = int.Parse(stringNumber);
return (T)(object)ad_id;
}
because I tried your sample and I get a return int.
You really don't have any way, currently, of ensuring your return is going to work. You method will rely on very specific information. Provide a bit more info where you have the ellipses and a better solution can be recommended. As Jon mentions, a nullable int? would be better. Test for the condition and if it isn't a correct return, you can check for myInt.HasValue.
I have been pondering a complete solution this problem and came up with the following:
static List<Type> numerics = new List<Type>();
static void Main(string[] args)
{
numerics.Add(typeof(Decimal));
numerics.Add(typeof(Double));
numerics.Add(typeof(Int16));
numerics.Add(typeof(Int32));
numerics.Add(typeof(Int64));
numerics.Add(typeof(Single));
numerics.Add(typeof(UInt16));
numerics.Add(typeof(UInt32));
numerics.Add(typeof(UInt64));
Console.WriteLine("StringNumber 55: {0} {1}", typeof(int), GetItemIdFromUrl<int>("55"));
Console.WriteLine("StringNumber 5B99: {0} {1}", typeof(int), GetItemIdFromUrl<int>("5B99"));
Console.ReadKey();
}
public static T GetItemIdFromUrl<T>(string stringNumber)
{
try
{
if (numerics.Contains(typeof(T)))
return (T)Convert.ChangeType(stringNumber, typeof(T));
else
return default(T);
}
catch (ArgumentException argEx)
{
Console.WriteLine("Exception\r\n{0}", argEx);
return default(T);
}
catch (FormatException formatEx)
{
Console.WriteLine("Exception\r\n{0}", formatEx);
return default(T);
}
}
From the 2nd WriteLine you will be able to see what happens if an invalid numeric is passed. Of course, I included the Exception messages just so you could see what they would return. It might not be a glamorous solution, but I think it is viable.
I also came up with this:
public static class GetNumeric<T>
{
public static Func<string, T> Value = stringValue => (T)Convert.ChangeType(stringValue, typeof(T));
}
Although I would still wrap the call in a try/catch block.

Related

Aggregate: Seed with a null value [duplicate]

private static Matcher<T> EqualTo<T>(T item)
{
return new IsEqual<T>(item);
}
How do I modify the above method definition such that the following are valid/allowed.
EqualTo("abc");
EqualTo(4);
EqualTo(null); // doesn't compile. EqualTo<string>(null) does
Trying to port some Java code where null seems to be acceptable value for a T parameter.
Update
Thanks: for all the answers - especially Eamon and Jason. I didn't want the method calls to bother with type-inference. The following overload fixed it.
private static Matcher<object> EqualTo(object item)
{
return EqualTo<object>(item);
}
Actually the above question was a part of a larger puzzle. The end goal was for the following to work.
this.AssertThat(null, EqualTo(null));
this.AssertThat(null, Not(EqualTo("hi")));
this.AssertThat("hi", Not(EqualTo(null)));
Applied the same fix.. RFC. (Ignore the ugly extension method part - that's another problem. Wanted to have these methods in all test-fixtures without inheritance.)
public static void AssertThat<T>(this object testFixture, object actual, Matcher<T> matcher, string message = "")
{
AssertThat(anyObject, (T)actual, matcher, message);
}
public static void AssertThat<T, TSuper>(this object testFixture, T actual, Matcher<TSuper> matcher, string message = "") where T : TSuper
{
... check and assert
Consider the following method:
public bool IsNullString<T>(T item) {
return typeof(T) == typeof(string) && item == null;
}
Yes, this is a pathetically stupid method and using generics is pointless here, but you'll see the point in a moment.
Now consider
bool first = IsNullString<string>(null);
bool second = IsNullString<Foo>(null);
bool third = IsNullString(null);
In the first and second, the compiler can clearly distinguish the type of T (no inference is needed). In the third, how the compiler infer what T is? In particular, it can't distinguish between T == string and T == Foo, or any other type for that matter. Therefore, the compiler has to give you a compile-time error.
If you want to get around this, you either need to cast null
EqualTo((object)null);
or explicitly state the type
EqualTo<object>(null)
or define an overload
private static Matcher<object> EqualTo(object item) {
return new IsEqual<object>(item);
}
Not possible without explicitly specifying a T or doing a cast. Generics are compile time constructs and as such if the compiler can't figure out the type at compile time, then it won't compile (as you're seeing).
Since you can't do exactly what you are wanting to do, how about defining an EqualTo(object) overloaded method? That should allow your required syntax.
You may work around this limitation by using the following syntax:
EqualTo("abc");
EqualTo(4);
EqualTo(default(object));
//equivalently:
EqualTo((object)null);
default(T) is the value a field of type T has if not set. For reference types, it's null, for value types it's essentially memory filled with zero bytes (...which may mean different things for different types, but generally means some version of zero).
I try to avoid the null everywhere in my code nowadays. It hampers type inference elsewhere too, such as with the var declared field and in a ternary operator. For example, myArray==null ? default(int?) : myArray.Length is OK, but myArray==null ? null : myArray.Length won't compile.
Maybe implementing a non-generic EqualTo, which takes an Object as the argument type, would solve the issue of rewriting those code lines.

Best way to convert object typed data to value type

I was tasked to create code that would fetch data from database using data reader and I'm curious of what is going to be the best practice between the 3 methods that I could use below to convert data from my data reader which by default fetched with a type of object.
internal static RoomType SelectRoomType(int roomTypeID)
{
SqlCommand commRoomTypeSelector = ConnectionManager.MainConnection.CreateCommand();
commRoomTypeSelector.CommandType = CommandType.StoredProcedure;
commRoomTypeSelector.CommandText = "Rooms.asp_RMS_RoomType_Select";
commRoomTypeSelector.Parameters.AddWithValue("RoomTypeID", roomTypeID);
SqlDataReader dreadRoomType = commRoomTypeSelector.ExecuteReader();
if (dreadRoomType.FieldCount != 0)
{
dreadRoomType.Read();
RoomType roomType = new RoomType();
roomType.RoomTypeID = (int)dreadRoomType["RoomTypeID"];
roomType.RoomTypeName = (string)dreadRoomType["RoomType"];
roomType.IsActive = ((string)dreadRoomType["IsActive"]).ToUpper() == "Y";
roomType.LastEditDate = (string)dreadRoomType["LastEditDate"] != string.Empty ? DateTime.Parse((string)dreadRoomType["LastEditDate"]) : DateTime.MinValue;
roomType.LastEditUser = (string)dreadRoomType["LastEditUser"];
dreadRoomType.Close();
return roomType;
}
dreadRoomType.Close();
return null;
}
What confuses me here is the unboxing part, According to http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx Boxing and Unboxing is quite expensive and should be avoided. I know that i could use
int.Parse(dreadRoomType["RoomTypeID"].ToString())
instead of
roomType.RoomTypeID = (int)dreadRoomType["RoomTypeID"];
The question is are there still ways of converting this data in a much more efficient way that both of this option and if there are no possible ways which of the two ways do you prefer to use. Thanks in advance all help and suggestions are accepted :)
You can use SqlDataReader.GetInt32() to avoid having to convert/parse to int again, for this you do have to know at what index the integer is within the columns selected though:
roomType.RoomTypeID = dreadRoomType.GetInt32(0);
Boxing isn't that expensive.
Other alternatives won't help; once you have an object, it's already boxed.
String parsing in particular is probably much more expensive than boxing. (although I haven't measured)
If a typed API exists, you can use it to avoid boxing (eg, calling GetInt32).
(although these typed methods are sometimes just wrappers around the untyped method so that they box too)
Bottom line: Don't worry about it.
That guideline is telling you to avoid boxing things in the first place by using typed (generic) collections where possible
If boxing/unboxing is "slow" (it really isn't)... why would converting to a string and back not be terribly slow? (It really is a waste: boxing/unboxing is significantly faster.) I would first make sure there is a performance problem, before worrying about it, however...
In my experience, for my data, which includes thousands of items loaded at once, I found that much more performance can be gained with pre-determining the column indices (but do so dynamically with GetOrdinal!), and then I don't worry about the rest :)
For one item, as per this post, I wouldn't even worry about ordinals: it's an entirely different use-case and the "expensive" part is talking to the database.
Happy coding.
Boxing and unboxing are not as expensive as parsing a string and extracting an int. Please profile before doing premature optimization.
private static void GetValue<T>(object o, ref T defaultValue)
{
try
{
if (defaultValue == null)
{
throw new Exception("Default value cannot be null");
}
else if (o != null)
{
if ((o is T))
{
defaultValue = (T)o;
}
}
}
catch (Exception)
{
throw;
}
}
You can use the above method to Convert an object to any basic data type as follows.
Convert to dateTime
public static DateTime GetDateTime(object o, DateTime defaultValue)
{
try
{
GetValue<DateTime>(o, ref defaultValue);
return defaultValue;
}
catch (Exception)
{
throw;
}
}
Convert to Integer
public static int GetInteger(object o, int defaultValue)
{
try
{
GetValue<int>(o, ref defaultValue);
return defaultValue;
}
catch (Exception)
{
throw;
}
}
Refer and download the complete code with all basic data types here
http://www.dotnetlines.com/Blogs/tabid/85/EntryId/39/Convert-Object-type-into-its-specific-data-type-using-a-Generic-Method.aspx

Any way to implement 'is'/'as' for dynamic or at least fake it?

I have a type ConfigValue that exposes a dynamic interface via an implementation of IDynamicMetaObjectProvider and custom DynamicMetaObject instance.
An instance of this type can be seen, of course, as it's native type - analogous to an XML Element - but it can also be seen as an instance of any other object type, according to the contents of the XML and what kind of object it builds (it's a proprietary IOC built by little old me).
So
<value>10</value>
Can be seen as a ConfigValue but also potentially a string, short, double etc. Conversion is achieved by implicit or explicit cast, as specified by the calling language. The XML gets more complicated because you can fire constructors, methods, property gets etc.
To achieve this, of course, I have overriden the BindConvert member of the DynamicMetaObject type - and if the conversion is unsupported by the ConfigValue object at runtime, then a runtime error occurs (which is fine).
I've just started writing a piece of code where it would be great if I could do a safe cast to the target type, but if that doesn't work fallback to some other logic - analogous to:
public DesiredType Foo(dynamic d)
{
DesiredType dt = d as dt;
if(dt != null)
return dt;
//TODO: Fallback logic to build dt from d
}
But, C# at least (and probably all dynamic-aware languages I'm sure) doesn't emit any dynamic binding for the 'as' or 'is' operations; presumably because DynamicMetaObject doesn't have a method for such a test. Thus the type test is just performed on the static type information which, in this case, always fails.
As a result I'm having to rely on the rather ugly:
public DesiredType Foo(dynamic d)
{
try
{
return (DesiredType)d;
}
catch(Exception)
{
//TODO: fallback logic
}
}
Any ideas how I can avoid the try/catch/gulp pattern here!? The best I can think of is something on top of DynamicMetaObject; but then that has to be queried for first, before then being queried again for the type test; which is just going to explode the code up even further!
I don't think it is possible.
Take for example, this code:
class Program
{
static void Main(string[] args)
{
dynamic d = new object();
var x = (Program)d;
Console.WriteLine(x);
var y = d as Program;
Console.WriteLine(y);
var z = d is Program;
Console.WriteLine(z);
}
}
If we decompile it using Reflector we see that the only reason that the cast is able to be intercepted by the dynamic type is that the C# compiler does a lot of extra work in order to support it:
class Program
{
private static void Main(string[] args)
{
object d = new object();
if (<Main>o__SiteContainer0.<>p__Site1 == null)
{
<Main>o__SiteContainer0.<>p__Site1 = CallSite<Func<CallSite, object, Program>>.Create(Binder.Convert(CSharpBinderFlags.ConvertExplicit, typeof(Program), typeof(Program)));
}
Console.WriteLine(<Main>o__SiteContainer0.<>p__Site1.Target(<Main>o__SiteContainer0.<>p__Site1, d));
Program y = d as Program;
Console.WriteLine(y);
bool z = d is Program;
Console.WriteLine(z);
}
}
In contrast, the as and is calls are simply compiled down to IL instructions, with no added magic from the C# compiler.
This fits in with the normal casting operators as well; using as rather than a cast will not perform any conversion casts, so will never change the type of the underlying object.
is and as are runtime tests that only work on inheritance, thus they don't need to dynamically bind because they are already dynamic. Even without the dynamic keyword you could never use is or as to test for implict or explicit conversions, and they never would work on value types like short and double either.
So your answer is that there is no need to fake it, they work exactly the same for dynamic types as static types. Your try catch is probably the best way to test the conversion, catching binding errors is what the DLR is already doing in the background for a lot of it's fallback cases. You can see for yourself in the debugger if you stop on first chance exceptions.
The best way to improve your try catch would be to specify the exact exception.
catch(RuntimeBinderException)
{
//TODO: fallback logic
}
In lieu of the fact that it's not supported, I've written this very basic static method to simplify the operation of testing the conversion.
public static class DynamicHelper
{
public static TResult As<TResult>(dynamic obj) where TResult : class
{
if (obj == null)
return null;
try
{
return (TResult)obj;
}
catch (Exception)
{
return null;
}
}
}
It's top-drawer code that ;)

What's the point of "As" keyword in C#

From the docs:
The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form:
expression as type
is equivalent to:
expression is type ? (type)expression : (type) null
except that expression is evaluated only once.
So why wouldn't you choose to either do it one way or the other. Why have two systems of casting?
They aren't two system of casting. The two have similar actions but very different meanings. An "as" means "I think this object might actually be of this other type; give me null if it isn't." A cast means one of two things:
I know for sure that this object actually is of this other type. Make it so, and if I'm wrong, crash the program.
I know for sure that this object is not of this other type, but that there is a well-known way of converting the value of the current type to the desired type. (For example, casting int to short.) Make it so, and if the conversion doesn't actually work, crash the program.
See my article on the subject for more details.
https://ericlippert.com/2009/10/08/whats-the-difference-between-as-and-cast-operators/
Efficiency and Performance
Part of performing a cast is some integrated type-checking; so prefixing the actual cast with an explicit type-check is redundant (the type-check occurs twice). Using the as keyword ensures only one type-check will be performed. You might think "but it has to do a null check instead of a second type-check", but null-checking is very efficient and performant compared to type-checking.
if (x is SomeType )
{
SomeType y = (SomeType )x;
// Do something
}
makes 2x checks, whereas
SomeType y = x as SomeType;
if (y != null)
{
// Do something
}
makes 1x -- the null check is very cheap compared to a type-check.
Because sometimes you want things to fail if you can't cast like you expect, and other times you don't care and just want to discard a given object if it can't cast.
It's basically a faster version of a regular cast wrapped in a try block; but As is far more readable and also saves typing.
It allows fast checks without try/cast overhead, which may be needed in some cases to handle message based inheritance trees.
I use it quite a lot (get in a message, react to specific subtypes). Try/cast wouuld be significantly slower (many try/catch frames on every message going through) - and we talk of handling 200.000 messages per second here.
Let me give you real world scenarios of where you would use both.
public class Foo
{
private int m_Member;
public override bool Equals(object obj)
{
// We use 'as' because we are not certain of the type.
var that = obj as Foo;
if (that != null)
{
return this.m_Member == that.m_Member;
}
return false;
}
}
And...
public class Program
{
public static void Main()
{
var form = new Form();
form.Load += Form_Load;
Application.Run(form);
}
private static void Form_Load(object sender, EventArgs args)
{
// We use an explicit cast here because we are certain of the type
// and we want an exception to be thrown if someone attempts to use
// this method in context where sender is not a Form.
var form = (Form)sender;
}
}
I generally choose one or the other based on the semantics of the code.
For example, if you have an object that you know that it must be an string then use (string) because this expresses that the person writing the code is sure that the object is a string and if it's not than we already have bigger problems than the runtime cast exception that will be thrown.
Use as if you are not sure that the object is of a specific type but want to have logic for when it is. You could use the is operator followed by a cast, but the as operator is more efficient.
Maybe examples will help:
// Regular casting
Class1 x = new Class1();
Class2 y = (Class2)x; // Throws exception if x doesn't implement or derive from Class2
// Casting with as
Class2 y = x as Class2; // Sets y to null if it can't be casted. Does not work with int to short, for example.
if (y != null)
{
// We can use y
}
// Casting but checking before.
// Only works when boxing/unboxing or casting to base classes/interfaces
if (x is Class2)
{
y = (Class2)x; // Won't fail since we already checked it
// Use y
}
// Casting with try/catch
// Works with int to short, for example. Same as "as"
try
{
y = (Class2)x;
// Use y
}
catch (InvalidCastException ex)
{
// Failed cast
}

which is better, using a nullable or a boolean return+out parameter

Lets say I have a function that needs to return some integer value. but it can also fail, and I need to know when it does.
Which is the better way?
public int? DoSomethingWonderful()
or
public bool DoSomethingWonderful(out int parameter)
this is probably more of a style question, but I'm still curious which option people would take.
Edit: clarification, this code talks to a black box (lets call it a cloud. no, a black box. no, wait. cloud. yes). I dont care why it failed. I would just need to know if I have a valid value or not.
I like the nullable version better, because you can use the null coalesce operator ?? on it, e.g.:
int reallyTerrible = 0;
var mightBeWonderful = DoSomethingWonderful() ?? reallyTerrible;
It depends on how you think the calling code should look like. And therefore what your function is used for.
Generally, you should avoid out arguments. On the other hand, it could be nice to have code like this:
int parameter;
if (DoSomething(out paramameter))
{
// use parameter
}
When you have a nullable int, it would look like this:
int? result = DoSomething();
if (result != null)
{
// use result
}
This is somewhat better because you don't have an out argument, but the code that decides if the function succeeded doesn't look very obvious.
Don't forget that there is another option: use Exeptions. Only do this if the case where your function fails is really an exceptional and kind of a error-case.
try
{
// normal case
int result = DoSomething()
}
catch (SomethingFailedException ex)
{
// exceptional case
}
One advantage of the exception is that you can't just ignore it. The normal case is also straight forward to implement. If the exceptional case something you could ignore, you shouldn't use exceptions.
Edit: Forgot to mention: another advantage of an Exception is that you also can provide information why the operation failed. This information is provided by the Exception type, properties of the Exception and the message text.
Why not throw an exception?
I would follow the pattern used in some place in the .Net library like:
bool int.TryParse(string s, out value)
bool Dictionary.TryGetValue(T1 key, out T2 value)
So I would say:
public bool TryDoSomethingWonderful(out int parameter)
It really depends on what you are doing.
Is null a meaningful answer? If not, I would prefer a bool TryDoSomethingWonderful(out int) method call. This matches up with the Framework.
If, however, null is a meaningful return value, returning int? makes sense.
Unless performance is the primary concern you should return an int and throw an exception on failure.
I would use the second, because I probably need to know right away if the call succeeded, and in that case I would rather write
int x;
if( DoSomethingWonderful( out x ) )
{
SomethingElse(x);
}
than
int? x = DoSomethingWonderful();
if( x.HasValue )
{
SomethingElse(x.Value);
}
I am in favor of using an output parameter. In my opinion, this is the kind of situation for which use of an output parameters is most suited.
Yes, you can use the coalesce operator to keep your code as a one-liner if and only if you have an alternative value that you can use in the rest of your code. I often find that is not the case for me, and I would prefer to execute a different code path than I would if I was successfully able to retrieve a value.
int value;
if(DoSomethingWonderful(out value))
{
// continue on your merry way
}
else
{
// oops
Log("Unable to do something wonderful");
if (DoSomethingTerrible(out value))
{
// continue on your not-so-merry way
}
else
{
GiveUp();
}
}
Additionally, if the value that I want to retrieve is actually nullable, then using a function with an output parameter and a boolean return value is, in my opinion, the easiest way to tell the difference between "I was unsuccessful in retrieving the value" and "The value I retrieved is null". Sometimes I care about that distinction, such as in the following example:
private int? _Value;
private bool _ValueCanBeUsed = false;
public int? Value
{
get { return this._Value; }
set
{
this._Value = value;
this._ValueCanBeUsed = true;
}
}
public bool DoSomethingTerrible(out int? value)
{
if (this._ValueCanBeUsed)
{
value = this._Value;
// prevent others from using this value until it has been set again
this._ValueCanBeUsed = false;
return true;
}
else
{
value = null;
return false;
}
}
In my opinion, the only reason most people tend not to use output parameters is because they find the syntax cumbersome. However, I really feel that using output parameters is the more appropriate solution to this problem, and I found that once I got used to it I found the syntax much preferable to returning a null value.
If there's only one way it can fail, or if you'll never need to know why it failed, I'd say it's probably simpler and easier to go with the nullable return value.
Conversely, if there are multiple ways it could fail, and the calling code could want to know exactly why it failed, then go with the out parameter and return an error code instead of a bool (alternatively, you could throw an exception, but based on your question, it seems you've already decided not to throw an exception).
You should rather then use a try catch. This seems like the caller does not know what might happen?
Should we check both bool and the out, or should i check both returns null and the actual return.
Let the method do what it should, and in the case where it failed, let the caller know that it failed, and the caller hanlde as requied.
Interestingly enough, my personal opinion sways significantly based on the nature of the method. Specifically, if the method's purpose is to retrieve a single value, as opposing to "doing something".
Ex:
bool GetSerialNumber(out string serialNumber)
vs
string GetSerialNumber() // returns null on failure
The second feels more "natural" to me somehow, and likewise:
bool GetDeviceId(out int id)
vs
int? GetDeviceId() // returns null on failure`
But I admit this really falls into "coding style" territory.
Oh, and I, too, would tend to favor exception throwing:
int GetDeviceId() // throws an exception on read failure
I'm still not sold on why they'd be so wrong. Can we have a thread on that, Oren? ;-)
I dislike Microsoft's "Try" pattern in which the "out" parameter is used to return a data item. Among other things, methods coded in that fashion cannot be used in covariant interfaces. I would rather see a method coded as: T GetValue(out bool Successful) or perhaps T GetValue(out GetValueErrorEnum result); or T GetValue(out GetValueErrorInfo result); if something beyond a true/false might be needed. Since every data type has a legal default value, there's no problem with deciding what to return if the function fails. Calling code can easily say:
bool success;
var myValue = Thing.GetValue(ref success);
if (success)
.. do something using myValue
else
.. ignore myValue
It would be nice if .net and C# offered true covariant 'copy out' parameters (the caller would allocate space for the result, pass a pointer to that space to the called function, and then copy the allocated space to the passed-in variable only after the function returned).

Categories

Resources