How to automatically cast variables in C#? - c#

Here is a example.
var tobeCasted = 1;
object data = null;
if (whatIsMyType == typeof(int)) {
data = (int)tobeCasted;
}
else if (whatIsMyType == typeof(float)) {
data = (float)tobeCasted;
}
However the above code is manually detected each data type.
I'm looking for a one line general solution like following :
data = (whatIsMyType)tobeCasted;

Use the Convert.ChangeType method. The documentation for the Convert class is here; it contains many useful methods for runtime type coercion.
http://msdn.microsoft.com/library/system.convert.aspx
That said, try to avoid this if you can. This kind of runtime typing can be considered a bad code smell.

In this particular case, I think you want Convert.ChangeType:
object data = Convert.ChangeType(toBeCasted, whatIsMyType);
Of course that only works with a limited set of types - but then so does casting in the first place. If you can tell us more about what you're trying to do, it would be helpful. There may very well be a better approach.

If you're sticking the result into a variable of type Object, just do that. As you have it now, you're casting to int/float/whatever, then casting to Object. Cut out the middle man.
var tobeCasted = 1;
object data = tobeCasted;

Your example is too trivial to understand your real need, but Maybe something like TypeMapper is more suited for your use.

Related

Lazy<T> as Lazy<object> possible?

Is it possible to cast a Lazy<T> instance as a Lazy<object> when all I have is an object reference?
This returns null:
var result = obj as Lazy<object>;
That makes sense to me. It should be null because its not a Lazy<object>. But is there another way to interrogate to find out what T actually is or cast to object? I actually don't care what T actually is in this case. I just need the .Value reference.
Some background
So this is really a curiosity question. It could be applied to any object specifying a generic (i.e. List<T>). But here's the specific case:
I'm sticking a Lazy<T> provider in a cache. I know what T is when I put it in and I know what T is in the normal use when i pull it out.
However, in one case when I'm managing the cache, I don't know what T is and really I don't want to interact with it except to send its value to a serializer. I'm just concerned I'm missing some obvious way to achieve this without creating a way to track it ahead of time or change a bunch of method signatures/calls.
This is what the dynamic keyword is for. It uses the same reflection solution underneath as #SledgeHammer's answer, except that it has a cache for the getter delegates so it's a lot faster if you do it more than once for the same T. It's also a lot shorter and easier to read (and write).
object result = (obj as dynamic).Value;
The way you asked the question, you would need to use reflection (or expression trees) to do it:
Lazy<int> l = new Lazy<int>(() => 5);
object o = l;
object val = o.GetType().GetProperty("Value").GetGetMethod().Invoke(o, null);
Classes in C# cannot be covariant, so there is no way for you to treat that object instance as a Lazy<object>. You'll have to create a new Lazy object that simply uses the other Lazy to determine what the value should be. Doing so is simple enough:
Lazy<T> oldLazy = ComputeOldLazy();
Lazy<object> newLazy = new Lazy<object>(() => oldLazy.Value);

How to get elements from simple array in C#?

I need to get values of my enum, so I am using following command:
Array a = Enum.GetValues(typeof(Typ));
However, typical expression
a[x]
does not work, why?
Thanks
Well, because Enum.GetValues is not generic.
If you write:
var a = Enum.GetValues(typeof(Typ));
Console.WriteLine(a.GetType());
You'll get: "Namespace.Typ[]". But because method is not generic, compiler can't change returning type basing on supplied type, so the method returns System.Array which is base type for arrays and you have to use type casts to downcast it to expected type, for example:
Typ[] a = (Typ[])Enum.GetValues(typeof(Typ));
The proper way in my opinion to do it is:
Array a = Enum.GetValues(typeof(Typ));
and then retrieve elements at positions by:
a.GetValue(elementsIndex);
I've used the following code to handle emums when converting a custom classes for DB SP params, works all the time.
public static object ParamValue<T>(Enum value)
{
if (value == null)
return System.DBNull.Value;
else
return (T)Enum.Parse(value.GetType(), value.ToString());
}
Based on OPs comments, he might not actually be interested in the values of the Enum, but instead of the names. The distinction can easily be confusing to beginners. Tip: When you ask questions involving an error (i.e. "does not work, why?"), then including the error message often helps.
If you are looking for the names in the Enum, try:
string[] names = Enum.GetNames(typeof(Typ));

Cast Boxed Object back to Original Type

I expect there's one of two answers to this, either impossible or extremely simple and I've overlooked the obvious Google query.
The underlying issue is that I have a generic object being passed in via an EventHandler that boxes the object and obfuscates the true type; only at runtime do I know what the object is.
Admittedly the dynamic keyword can get around the issue, but I'd like to not lose IntelliSense and everything if I can avoid it. Plus, it doesn't solve not knowing what each of the properties of the generic object are without massive amounts of reflection.
EDIT: The idea is to be able to determine the true type of the an object in a method parameter, and then cast that object as it's true type without knowing it in advance. This is but a simplified example. Boxed may have been the wrong term.
An example:
public class Program
{
static void Main(string[] args)
{
var container = new Container<Containee>(
new Containee
{
Property1 = Guid.NewGuid(),
Property2 = "I'm a property!",
Property3 = DateTime.Now
}
);
var boxed = (object)container;
var originalType = boxed.GetType();
// DOES NOT COMPILE: would like an operation like this
// EDIT: Request for more detail
var actualType = boxed as originalType;
actualType.Entity.Property2 = "But I like this better.";
}
}
public class Containee
{
public Guid Property1 { get; set; }
public string Property2 { get; set; }
public DateTime Property3 { get; set; }
}
public class Container<T>
{
public Container(T entity)
{
Entity = entity;
}
public T Entity { get; internal set; }
}
Clearly that won't compile, as there's not really a way to cast as a variable. However, I'm hoping there's a way to get a reference to the actual object and type, or at least, a way to dynamically re-create the type.
I expect there's something simple I'm overlooking, or a better way to get around it in general. The point is to be able to wrap any object in the container, and figure out later what it was.
The idea is to be able to determine the true type of the an object in a method parameter
That's easy enough (and you're already doing it).
Type actualType = param.GetType();
That will get you the actual concrete type of the object
and then cast that object as it's true type
This is where things come off the rails a bit. The casting operator in C# (usage of which is what people refer to as "casting") can do two things:
Use type-specific explicit conversions to create a new object by applying the conversion to the existing object (note that this is a new reference that is created; the original object's type is never changed)
Allow the developer to reference an object as a type that is at a different level in its inheritance hierarchy than is currently provided (or an interface that is implemented on a type that is lower in the hierarchy than is currently referenced)
In your case, the first option is right out; the casting operator, like all operators, is not polymorphic. That is, an operator is only applied if it is defined on the type that is being referenced, not the object that's being referenced. If you'd like further clarification on this, let me know, but I don't think it's germane to your question so I'm not going to go into it further unless asked.
The second option is the only option that could realistically apply to you, but consider the only two reasons you would want to do this:
So that you can refer to the object as a specific concrete type that is at a lower level than is currently provided (in your case, your object is an object, so that's pretty much as high as it goes)
So that you can refer to an object as a type that is higher in the hierarchy so that you can bypass hidden (but not overridden) members.
(The vast majority of casts are for reason #1)
The reason you would want to use either of those options is so that you can have a strongly-typed object and use the various members defined on that type. But all of these things only apply to types that you know when you're writing the code. It doesn't make sense to cast to a type that is unknown at compile time, as casting doesn't do anything to the actual object (it is, and shall remain, its true type; the only thing that changes is the type of the variable by which you reference the object).
If you can provide a further fleshed-out example of what you're actually trying to do (complete with code as you'd either like or expect it to work), I might be able to provide something modeled a little closer to what you want, but as it's described this is as specific as I can get.
First of all: That's not "boxing". Boxing is for value types, like structs.
Second of all: What you probably need is either:
Compile-time reflection, which C# doesn't have
Dynamic code generation, which you can do (painfully) with Reflection.Emit.
Third of all: Your sample code does variable1 as variable2, which doesn't really make sense. :\ What are you intending to do after that? Perhaps there's a better way.
You could use dynamic:
dynamic actualType = boxed;
actualType.Entity.Property2 = "But I like this better.";
This should compile and work.
var actualType = boxed as originalType;
Just so we're on the same page, let me explain why this is impossible.
var is a compile time construct. It is, identical to declaring the variable with the proper type straight off. Besides being easier to type, it's main use is for anonymous types which, as implied, have no names.
Anyway, to get to the meat of your question, your best bet is to use Dynamic code generation, either with Reflection.Emit or CodeDom (the latter is much easier to understand if you don't know ILASM, but is much slower).
Depending on what you actually want to do, you might be able to get away with something like
if(someObject is Container<Containee>) {
var container = (Container<Containee>)someObject;
//...
}
But, if you can expect literally any type, well... good luck.
The underlying issue is that I have a
generic object being passed in via an
EventHandler that boxes the object and
obfuscates the true type; only at
runtime do I know what the object is.
How do you want to handle it, if the type is only known at runtime? You can't call any specific class methods because you won't know the exact type anyway, unless all objects share some set of methods which can be extracted as interface.
Basically, you have several options:
Use is and do different things for different types:
object value = GetValue ();
if (value is Program)
((Program)value).Run ();
else if (value is Animal)
((Animal)value).Run ();
If all possible types are supposed to share a set of operations, use an interface:
object value = GetValue ();
IRunnable runnable = (IRunnable)value;
runnable.Run ();
Rephrase your question and extend your sample with how you see it working after you've done the ‘magical casting’. This would give us the idea what you're trying to accomplish.

A List of varying types?

Id' like to create a list of data that will be passed from method to method, however I can't use a struct because the data that will be contained in this list will vary depending on the input.
For example
if (x == 1) {
a = 1
b = true
c = 42
d = "hello"
}
if (x == 2) {
a = 2
b = 'g'
c = "sup"
}
I believe my options are thus:
Create an array or List of strings, and cast the data back to what it originally was from strings. This is messy and could lead to bugs of uninterpretable input, though wouldn't be so bad since it'd all be detected at runtime.
Create a struct for each possibility - Is this even good practice?
Somehow use generics. From what I know, while generics are type-safe yet not type-strict, they must be cast to types before being used. Eg if I wanted a List of items here, I'd need to cast them to strings much like would happen with solution 1, making this useless.
My question then, is which of these options is the best? Or is there an alternate option using some sort of generic type I don't know about? The number of possible variables in each case may change, as with their types. I'd like to be able to return a single List or Array to the calling method, so that it may appropriately deal with the result. It will know how to deal with each group of data based on the value of a, as it will be the 'action choice' identifier. I'm also aware that casting them to objects and back each time is very intensive so I'd rather avoid that.
This is probably pretty simple but it has me stumped...
Since you don't know before hand what the list will contain, it looks like a good case for using an ArrayList.
If you want to get back to the values using a key, consider using a Hashtable.
The general principal in .NET is that every type can be cast to System.Object (although it may involve boxing). You can use a method like
void Foo(params object[] parameters) { ... }
Or use the System.Collections.ArrayList class.
The 'problem' is that when you want to use such a value, you will need code like:
if (parameters[i] is string)
{
string s = (string) parameters[i];
...
}
Sorry, this is not a code related answer: there may be a faulty design hidden behind such a construct. Make sure you know what you are doing, otherwise things might fire back.
If not knowing the type of the fields you use beforehand really is required, this calls for an approach that saves the data with their type, like
struct foo {
private object _value;
private string _type;
foo(string myType, object myValue) {
_value = myValue;
_type = myType;
}
}
and then using Generics to handle the business logic.
Basically you need a list typed to Object, and then yes, you're in a mode of casting back.
My question is, structurally, how will you know what indexes are of which type? This sounds like a painful solution at best.
If you really need to store differing types in the list, perhaps try a struct which contains a member of each type, as well as a flag indicating which data type is represented. Then use a generic collection for that struct. Something like (off the top of my head)
struct FooType
{
public string StringValue;
public bool BoolValue;
public int IntValue;
public char CharValue;
public string DataType;
// You'd probably want constructors too
}
Then the generic list:
var values = new List<FooType>();
Now you can add and remove entries in the list using that type, which would then indicate what the core data really is.
I still don't like the answer; it sounds like your design may be trying to do too much and there may be refactoring opportunities, but since I don't see much more of your code or intent, all I can do is answer what you've asked. :)
You could represent the data items using a Dictionary/Hashtable and then add these dictionaries to a List.
You could also add extra type information into the dictionary value if needed.

Mark parameters as NOT nullable in C#/.NET?

Is there a simple attribute or data contract that I can assign to a function parameter that prevents null from being passed in C#/.NET? Ideally this would also check at compile time to make sure the literal null isn't being used anywhere for it and at run-time throw ArgumentNullException.
Currently I write something like ...
if (null == arg)
throw new ArgumentNullException("arg");
... for every argument that I expect to not be null.
On the same note, is there an opposite to Nullable<> whereby the following would fail:
NonNullable<string> s = null; // throw some kind of exception
There's nothing available at compile-time, unfortunately.
I have a bit of a hacky solution which I posted on my blog recently, which uses a new struct and conversions.
In .NET 4.0 with the Code Contracts stuff, life will be a lot nicer. It would still be quite nice to have actual language syntax and support around non-nullability, but the code contracts will help a lot.
I also have an extension method in MiscUtil called ThrowIfNull which makes it a bit simpler.
One final point - any reason for using "if (null == arg)" instead of "if (arg == null)"? I find the latter easier to read, and the problem the former solves in C doesn't apply to C#.
I know I'm incredibly late to this question, but I feel the answer will become relevant as the latest major iteration of C# comes closer to release, then released. In C# 8.0 a major change will occur, C# will assume all types are considered not null.
According to Mads Torgersen:
The problem is that null references are so useful. In C#, they are the
default value of every reference type. What else would the default
value be? What other value would a variable have, until you can decide
what else to assign to it? What other value could we pave a freshly
allocated array of references over with, until you get around to
filling it in?
Also, sometimes null is a sensible value in and of itself. Sometimes
you want to represent the fact that, say, a field doesn’t have a
value. That it’s ok to pass “nothing” for a parameter. The emphasis is
on sometimes, though. And herein lies another part of the problem:
Languages like C# don’t let you express whether a null right here is a
good idea or not.
So the resolution outlined by Mads, is:
We believe that it is more common to want a reference not to be null. Nullable reference types
would be the rarer kind (though we don’t have good data to tell us by
how much), so they are the ones that should require a new annotation.
The language already has a notion of – and a syntax for – nullable value types. The analogy between the two would make the language
addition conceptually easier, and linguistically simpler.
It seems right that you shouldn’t burden yourself or your consumer with cumbersome null values unless you’ve actively decided that you
want them. Nulls, not the absence of them, should be the thing that
you explicitly have to opt in to.
An example of the desired feature:
public class Person
{
public string Name { get; set; } // Not Null
public string? Address { get; set; } // May be Null
}
The preview is available for Visual Studio 2017, 15.5.4+ preview.
I know this is a VERY old question, but this one was missing here:
If you use ReSharper/Rider you may use the Annotated Framework.
Edit: I just got a random -1 for this answer. That's fine. Just be aware it is still valid, even though it's not the recommended approach for C#8.0+ projects anymore (to understand why, see Greg's answer).
Check out the validators in the enterprise library. You can do something like :
private MyType _someVariable = TenantType.None;
[NotNullValidator(MessageTemplate = "Some Variable can not be empty")]
public MyType SomeVariable {
get {
return _someVariable;
}
set {
_someVariable = value;
}
}
Then in your code when you want to validate it:
Microsoft.Practices.EnterpriseLibrary.Validation.Validator myValidator = ValidationFactory.CreateValidator<MyClass>();
ValidationResults vrInfo = InternalValidator.Validate(myObject);
not the prettiest but:
public static bool ContainsNullParameters(object[] methodParams)
{
return (from o in methodParams where o == null).Count() > 0;
}
you could get more creative in the ContainsNullParameters method too:
public static bool ContainsNullParameters(Dictionary<string, object> methodParams, out ArgumentNullException containsNullParameters)
{
var nullParams = from o in methodParams
where o.Value == null
select o;
bool paramsNull = nullParams.Count() > 0;
if (paramsNull)
{
StringBuilder sb = new StringBuilder();
foreach (var param in nullParams)
sb.Append(param.Key + " is null. ");
containsNullParameters = new ArgumentNullException(sb.ToString());
}
else
containsNullParameters = null;
return paramsNull;
}
of course you could use an interceptor or reflection but these are easy to follow/use with little overhead
Ok this reply is a bit late, but here is how I am solving it:
public static string Default(this string x)
{
return x ?? "";
}
Use this exension method then you can treat null and empty string as the same thing.
E.g.
if (model.Day.Default() == "")
{
//.. Do something to handle no Day ..
}
Not ideal I know as you have to remember to call default everywhere but it is one solution.

Categories

Resources