In C#, you can append a question mark to a type to indicate that it may hold either a value of a type or return null:
double? MySqrt(double a)
{
return (a > 0.0) ? Math.Sqrt(a) : null;
}
Console.WriteLine(MySqrt(4.5)); // 2.1213203435596424
Console.WriteLine(MySqrt(-4.5)); // a blank line
Now, if I want to condition a variable assignment the result of this function, I can use the ?? operator, e.g.
double b = MySqrt(-2.0) ?? 0.0;
Console.WriteLine(b); // 0
But without redefining MySqrt, how can I control the larger programmatic flow (not just a single variable assignment) based on whether or not MySqrt returned null?
The following, for example, yields a compiler error:
void DrawSquareWithArea(double area)
{
double sideLength = MySqrt(area);
if (sideLength != null)
{
// Draw a square on the screen
DrawSquare(sideLength);
}
else
{
// Display some visual feedback indicating that input was invalid
DisplayErrorFeedback();
}
}
// error CS0266: Cannot implicitly convert type 'double?' to 'double'. An explicit conversion exists (are you missing a cast?)
Note that the function DrawSquare() requires a double argument here, so changing sideLength to a double? is another compiler error.
By using the correct type (Nullable<double> a.k.a. double?). The non-null value can be accessed by means of the Value property (which has type double here):
void DrawSquareWithArea(double area)
{
double? sideLength = MySqrt(area);
if (sideLength != null) // or: if (sideLength.HasValue)
{
// Draw a square on the screen
DrawSquare(sideLength.Value);
}
else
{
// Display some visual feedback indicating that input was invalid
DisplayErrorFeedback();
}
}
Or have the compiler infer the type:
var sideLength = MySqrt(area);
You can't convert explicitly double? to double. Either check for null and use .Value:
void DrawSquareWithArea(double area)
{
double? sideLength = MySqrt(area);
if (sideLength is not null)
{
// Draw a square on the screen
DrawSquare(sideLength.Value); // sideLength.Value is double
}
//...
}
or use pattern matching with declaration pattern:
void DrawSquareWithArea(double area)
{
if (MySqrt(area) is {} len) // checks for null and assigns variable of double type
{
// Draw a square on the screen
DrawSquare(len);
}
//...
}
or :
void DrawSquareWithArea(double area)
{
if (MySqrt(area) is double len) // checks for null and assigns variable of double type
{
// Draw a square on the screen
DrawSquare(len);
}
//...
}
Read more:
Nullable value types (C# reference)
Pattern matching overview
The other answers are perfectly fine. However I would like to add another approach which could be quite handy and (from my perspective) might be even better than using null as return type.
If your method is called with a non valid value why not simply throw an exception? In your calling method, handle the thrown exception. A minimal working example could look like the following.
class Program
{
static void Main(string[] args)
{
try{
MySqrt(-5);
} catch(Exception e) {
Console.WriteLine(e.Message);
}
}
static double MySqrt(double a)
{
if(a > 0.0) return Math.Sqrt(a);
throw new ArithmeticException("Can not calculate square root of negative value!");
}
}
Related
This question already has answers here:
What's the difference between the 'ref' and 'out' keywords?
(28 answers)
Closed 7 years ago.
I thought I understood the difference, but now I'm not so sure. I've read the technical answer several times but I'm not understanding what is happening. I have this example.
class Program
{
static void Main()
{
int val = 0;
Example1(val);
Console.WriteLine(val); // Still 0!
Example2(ref val);
Console.WriteLine(val); // Now 2!
Example3(out val);
Console.WriteLine(val); // Now 3!
}
static void Example1(int value)
{
value = 1;
}
static void Example2(ref int value)
{
value = 2;
}
static void Example3(out int value)
{
value = 3;
}
}
I always thought the difference between default parameters is that if I am passing val into Example1, I can't use assignment.
But with the ref keyword val is still 0, but I have created a reference that is now treated as the variable "value" within Example2(ref val). Am I getting hung up on anything so far? if I had used
int value = 0;
Example1(value);
Console.WriteLine(value); // this would then return 1 correct?
Now then, what is happening with the out keyword? Same thing as ref?
See if this helps:
No "decorators"
static void Example(int value)
{
Console.WriteLine("Value is {0}", value);
value = 99;
}
usage
{
int value = 10;
Example(notADefaultValue); // Will print <Value is 10>
Console.WriteLine("Value is {0}", value); // will print <Value is 10>
}
Summary: Value types (structs/enums/int/double/etc) are not passed in as a reference by default so whatever you do to the variable within a method does not affect the caller. Thus, the "ref" keyword. If you pass a reference type to a method (i.e. a class) and change it's internals, these will affect the caller.
Default parameters:
static void Example(int value = 5)
{
Console.WriteLine("Value is {0}", value);
}
usage
{
int notADefaultValue = 10;
Example(notADefaultValue); // Will print <Value is 10>
Example(); // will print <Value is 5>
}
Summary: Default values allow you to call a method without explicitly needing to pass parameters, the default value is used.
Ref parameters:
static void Example(ref int value)
{
Console.WriteLine("Value is {0}", value);
value = 99;
}
usage
{
int value = 10;
Example(ref value); // Will print <Value is 10>
Console.WriteLine("Value is {0}", value); // Will print <Value is 99>
}
Summary: If you pass a value type in as a ref (reference) the value itself gets changed. Allreference types are passed in as ref by default. FYI, int is a primitive types so needs an explicit "ref".
out parameters:
static void Example(out int value)
{
value = 99;
Console.WriteLine("Value is {0}", value);
}
usage
{
int value; // no need to init it
Example(out value); // Will print <Value is 99>
Console.WriteLine("Value is {0}", value); // Will print <Value is 99>
}
Summary: Out parameters are like return variables but passed in via the signature of the method. Most common example is TryParse where the method returns vital information and depending on that information the out parameter is either valid or not (valid if it is true).
In the first example you do not specify that the variable is a reference, and because it is a fundamental type, it just copies the provided number. So value inside Example1 is a copy of value in Main.
The second example uses a reference. This means the both inside the function Example2 and inside Main are refering to the same place in the memory, and therefore the value is transfered, when both entering and exiting the function.
In the third example, the out keyword does the same as the second except that is initialized to be 0 when entered into the function. As a result, it is just a parameter for returning some kind of data. The value is just transfered when exiting the function.
Ok, its a duplicate of the linked question in the comments but I'll try to explain it for you.
Undecorated Parameters
Case A: public void MyFunc(int x) { }
-or-
Case B: public void MyFunc(MyClass y) { }
In Case A, the parameter is a value type, and value types are, by default, passed as copies of the original value to the function. This doesn't mean you aren't allowed to modify the value, but the value will not be reflected back at the calling location. This is the same for all value types, the value is copied before it is passed to the function.
In Case B, the parameter is a reference type. These types are passed by default as they are. They are not copied, but you are not allowed to change the reference (by assigning a new or null value to the type). You can change the contents of the object (any property/field there-of) and it will be reflected back in the calling location.
The ref keyword
Case A: public void MyFunc(ref int x) { }
-or-
Case B: public void MyFunc(ref MyClass x) { }
In case A, you are telling the compiler that you want to pass the value by reference, which means the compiler will not copy the type, but passes a reference to that type. The function is allowed to change it.
In case B, you are telling the compiler that the function is allowed to change where the reference points to (you can create a new or set it to null and it will be reflected in the calling site.
The out keyword
Case A: public void MyFunc(out int x) { }
-or-
Case B: public void MyFunc(out MyClass x) { }
Here, you are basically defining additional return types for the function. Its the method parameter telling the caller to expect a result in the place of the x variable. This is the same for both. The caller should not expect, in any case, that any value that x was before, will be the same afterwards. In fact you can expect that it will not be the same, because the method is required to assign a new value to x before it is allowed to return.
out basically means you provide a place for a return value, for value types just use the default constructor and for reference types initialize the value to null before you pass it in.
Can somebody answer me this - why do I get this warning "The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'"
Here is the code
private char classLetter;
public char ClassLetter
{
get { return classLetter; }
set
{
if (classLetter == null)
{
classLetter = value;
RaisePropertyChanged("ClassLetter");
}
else throw new ArgumentOutOfRangeException();
}
}
If I use this code no warning comes in
private char classLetter;
public char ClassLetter
{
get { return classLetter; }
set
{
if (classLetter.ToString() == null)
{
classLetter = value;
RaisePropertyChanged("ClassLetter");
}
else throw new ArgumentOutOfRangeException();
}
}
In short my question is this
How can a int warning be given for a char variable?
EDIT: The 'char' should hold any latin or Cyrillic Letter, no special symbols and no numbers allowed. How should that be filtered?
In the first case, classLetter is of type char, which can never be null because it's a value type; it would need to be of type char?. So comparing classLetter == null doesn't make sense, as the compiler says.
In the second case, imagine classLetter is 'x'. When doing classLetter.ToString() you get "x", which can be compared with null because it is now a reference type. But again, this is not what you want because classLetter.ToString() will never be null.
If what you want is allowing to set the value only once, you can do this:
private char? classLetter = null; // make it nullable
public char ClassLetter
{
get {
if(classLetter == null) { // if we don't have a value yet
// do something, like throwing an exception
}else{ // if we do have a value already
return classLetter.Value; // here we return char, not char?
}
}
set
{
if (classLetter == null) {
classLetter = value;
RaisePropertyChanged("ClassLetter");
}
else throw new ArgumentOutOfRangeException();
}
}
A variable of type char is a value variable, not a reference variable, so it can never be null. Only variables of reference types can be null.
You get a warning because a value type will never be null. Full(er) explanation below.
A char in C# is a value type, and can never be null. Consider the purpose of char, that is to represent a Unicode character. There isn't really a good value to pick to mean null in the 0x0 to 0xFFFFFFFF range. (It's true that UTF-16 doesn't actually encompass this entire range, but it might someday).
It's a bit easy to understand with something that has a much smaller range. Consider a byte. It has a range of 0 - 255. Now, in order to represent null, we would need to pick a manner in which null could be stored. A few solutions end up coming up:
Store information extra to the byte to represent null. Nullable<Byte> does this.
Pick a value in the valid byte range to instead actually mean null. You end up needing to check for this value throughout an entire program. On a small scale, this is a non-issue, but when you don't know who's going to be using your code (a likely scenario), it's something you have to document and hope they see.
It's a much simpler implementation to provided non-nullable value types and a default and provide a wrapper around value types that can represent null if needed. .NET does exactly this with the Nullable<T> type and it's shortcuts with language support (int?,byte?, etc.).
To address your code, if classLetter really could be any value a char can represent, then you can use:
private char classLetter;
public char ClassLetter
{
get { return classLetter; }
set
{
classLetter = value;
RaisePropertyChanged("ClassLetter");
}
}
You can do this because the compiler will give the user a compile-time error if they try to do something to classLetter they couldn't possibly do sanely.
If you have additional requirement about what classLetter is supposed to represent, update your question and I'll update my answer.
In reponse to your comment on another answer: "I want the behavior to be simple. I want to be able to put any symbol, but I don't want the variable to be left empty"
The only other thing we need to settle on is what "empty" really means. What does empty mean in your context? Once you answer that, you can use default initialization in the type containing classLetter to set it to that value. A generalized example:
class Foo {
private char classLetter;
public char ClassLetter {
get { return classLetter; }
set {
classLetter = value;
}
}
public Foo(char classLetter = 'A') {
this.ClassLetter = classLetter;
}
}
When a caller uses new Foo(), they will get a Foo instance where Foo.ClassLetter == 'A'. Of course, A can be any sensible default that meets your specific requirements.
Is this what you want?
private char? classLetter;
public char ClassLetter
{
get { return classLetter.Value; // this will throw exception, if value hasn't set }
set
{
if (classLetter != null)
{
throw new InvalidOperationException("ClassLetter has been set already.");
}
classLetter = value;
RaisePropertyChanged("ClassLetter");
}
}
Note, that ArgumentOutOfRangeException doesn't fit this case. You don't make any tests for the range of argument.
This C++ code checks if o is a Node * and if so, calls a method on d.
if (Node * d = dynamic_cast<Node *>(o)) d->do_it();
What's the shortest and/or most efficient way to write the equivalent in C#?
Assuming that Node is a class then do the following
Node d = o as Node;
if (d != null) {
d.do_it();
}
If instead it's a struct then try this
if (o is Node) {
((Node)o).do_it();
}
As of C# 6 (July 2015), assuming Node is a class (or Nullable<T>, string, etc), using your example where you
check if o is a Node (not actually the same as converting o to a Node--see note about casting vs converting below)
if so, call do_it()
immediately discard the cast value
you can use the null-conditional operator:
(o as Node)?.do_it();
This syntax also handles the case where o is, in fact, declared as Node, but happens to be null.
If you want to keep the cast variable, as of C# 7 (March 2017), you can run:
if (o is Node node)
{
node.do_it();
}
The variable node at this point is in the scope outside of the if statement, equivalent to:
Node node = o as Node;
if (node != null)
{
node.do_it();
}
So, if you want to only continue the execution if o is a Node, you can write:
if (!(o is Node node))
{
return; // or continue, etc
}
node.do_it();
// ...
Note: The is keyword will always return false if o is null, even if you directly specify the type and then ask if that variable is that type.
string foo = null;
if (foo is string)
{
// never gets here
Console.WriteLine(foo);
}
Casting vs Converting
The is and as keywords do the same as C++'s dynamic_cast<T>: they will check against the specified type, subtype, or interface, but will not actually change the value in memory. They simply tell the compiler which methods should be available on the variable.
There's a misnomer amongst C# users where we use the words "cast" and "convert" interchangeably. This likely stems from the fact that we often know that a base type variable is always going to be a subtype, and so we use the convert syntax when puritanically we should be using the cast syntax:
void Foo(MyBaseType value)
{
// let's assume `value` will always be a MySubType
MySubType subTypeValue = (MySubType)value;
}
This syntax will throw at runtime if value is not, in fact, MySubType.
Converting differs from casting in that the value in memory may change. Consider int and double.
void Foo()
{
// implicit converting
int x = 1;
double y = x;
// explicit converting
y = 1.5;
x = (int)y;
}
In each of these cases, the literal value stored in memory changes format. ints can always be represented by a double--there will never be a loss in data--and so there is a defined implicit operator that will manipulate the data in memory into the new format. doubles, being floating point values and having a range larger than ints, cannot guarantee no loss in data, so C# requires an explicit conversion (usually termed "explicit cast") via the explicit operator to indicate to the compiler that we're okay with losing data.
With classes, we can define our own implicit and explicit operators which will manipulate the data whatever way we see fit. This is where the misnomer between convert and cast gets messy.
using System;
public class Program
{
public static void Main()
{
Foo foo = new Foo();
Bar bar = (Bar)foo;
// writes "1" (or would, if the program compiled)
Console.WriteLine(bar);
// throws compilation error: "Cannot convert type `Foo' to `Bar' via built-in conversion"
bar = foo as Bar;
// note: the same would happen if `foo` was type int? and `bar` was type `double?`
// even though double? can be converted to int?
}
}
class Foo
{
public readonly int Value = 1;
public static explicit operator Bar(Foo foo)
{
return new Bar(foo.Value.ToString());
}
}
class Bar
{
public readonly string Value;
public Bar(string value)
{
Value = value;
}
}
The as operator returns null if o is not a Node:
Node d = o as Node;
if (d != null)
{
d.do_it();
}
You can use the is keyword in C#.
if (o is Node)
{
}
I've got a generic type T. Using Marc's Operator class I can perform calculations on it.
Is it possible to detect by mere calculations whether the type is an integral or a nonintegral type?
Perhaps there is a better solution? I'd prefer to support any possible type, so I'd like to prevent hard-coding which types are integral/nonintegral.
Background info
The situation I find myself in is I want to cast a double to T but round to the nearest value of T to the double value.
int a = (int)2.6 results in 2 while I want it to result it in 3, without knowing the type (in this case int). It could also be double, in which case I want the outcome to be 2.6.
Have you tried Convert.ChangeType? Something like:
Convert.ChangeType(1.9d, typeof (T))
It will work for all numeric types I think (as long as the first parameter is iConvertible and the type is a supported one which all basic numerics should be I believe).
Its important to mention that this will call something like double.ToInt32 which rounds values rather than truncates (bankers rounding I believe).
I tested this in a little LinqPad program and it does what I think you want:
void Main()
{
var foo = RetNum<decimal>();
foo.Dump();
}
public static T RetNum<T>()
{
return (T)Convert.ChangeType(1.9d, typeof (T));
}
Here's a method which will determine if a particular value stored in a generic numeric type is an integer without hardcoding. Tested working for me on .NET 4. Correctly handles all built in numeric types (as defined in the MSDN link at the bottom) except BigInteger, which doesn't implement IConvertible.
public static bool? IsInteger<T>(T testNumber) where T : IConvertible
{
// returns null if T is non-numeric
bool? isInt = null;
try
{
isInt = testNumber.ToUInt64(CultureInfo.InvariantCulture) == testNumber.ToDouble(CultureInfo.InvariantCulture);
}
catch (OverflowException)
{
// casting a negative int will cause this exception
try
{
isInt = testNumber.ToInt64(CultureInfo.InvariantCulture) == testNumber.ToDouble(CultureInfo.InvariantCulture);
}
catch
{
// throw depending on desired behavior
}
}
catch
{
// throw depending on desired behavior
}
return isInt;
}
Here's a method which will determine whether a particular type is an integral type.
public static bool? IsIntegerType<T>() where T : IConvertible
{
bool? isInt = null;
try
{
isInt = Math.Round((double)Convert.ChangeType((T)Convert.ChangeType(0.1d, typeof(T)),typeof(double)), 1) != .1d;
// if you don't round it and T is float you'll get the wrong result
}
catch
{
// T is a non numeric type, or something went wrong with the activator
}
return isInt;
}
Convert.ChangeType is the way to convert, with rounding, between two generic numeric types. But for kicks and curiosity, here's a way to convert a generic numeric type to an int, which could be extended to return a generic type without too much difficulty.
public static int GetInt32<T>(T target) where T : IConvertible
{
bool? isInt = IsInteger<T>(target);
if (isInt == null) throw new ArgumentException(); // put an appropriate message in
else if (isInt == true)
{
try
{
int i = target.ToInt32(CultureInfo.InvariantCulture);
return i;
}
catch
{ // exceeded size of int32
throw new OverflowException(); // put an appropriate message in
}
}
else
{
try
{
double d = target.ToDouble(CultureInfo.InvariantCulture);
return (int)Math.Round(d);
}
catch
{ // exceeded size of int32
throw new OverflowException(); // put an appropriate message in
}
}
}
My results:
double d = 1.9;
byte b = 1;
sbyte sb = 1;
float f = 2.0f;
short s = 1;
int i = -3;
UInt16 ui = 44;
ulong ul = ulong.MaxValue;
bool? dd = IsInteger<double>(d); // false
bool? dt = IsInteger<DateTime>(DateTime.Now); // null
bool? db = IsInteger<byte>(b); // true
bool? dsb = IsInteger<sbyte>(sb); // true
bool? df = IsInteger<float>(f); // true
bool? ds = IsInteger<short>(s); // true
bool? di = IsInteger<int>(i); // true
bool? dui = IsInteger<UInt16>(ui); // true
bool? dul = IsInteger<ulong>(ul); // true
int converted = GetInt32<double>(d); // coverted==2
bool? isd = IsIntegerType<double>(); // false
bool? isi = IsIntegerType<int>(); // true
Additionally, this MSDN page has some example code which might be helpful. Specifically, it includes a list of types considered to be numeric.
I'm not 100% sure what you're asking, but:
To check if it's an integral type, use this: if (obj is float || obj is double), or if typeof(T) == typeof(float) || typeof(T) == typeof(double))
To check if it's an integral value, cast it to a double, and then do if(value == Math.Round(value))
Of course, that is assuming that you have a number in the first place. I believe that the Operator class you're using supports things like DateTime. Would it be better to make your generic method have a generic constraint where T : IConvertible? That way there'd be explicit ToDouble and ToInteger methods.
Edit:
I think I understand: you've got two local variables, double d; T num;. You want to cast d to type T, but with proper rounding if T is a integral type. Is that correct?
Assuming that's correct, here's what I'd do:
public void SomeMethod<T>()
{
double d;
// I think I got all the floating-point types. There's only a few, so we can test for them explicitly.
if(typeof(T) != typeof(double) && typeof(T) != typeof(float) && typeof(T) != typeof(Decimal))
{
d = Math.Round(d);
}
T converted = Convert.ChangeType(d, typeof(T));
}
Chris's answer gives a possible solution to the scenario I mentioned, but for performance reasons I am still attempting to answer the actual question.
The assumption (untested) is, Convert.ChangeType is much slower than Math.Round(). Ideally, I can check one time whether the given type is integral or not, and conditionally call Math.Round() from then on to obtain a much more efficient solution than calling Convert.ChangeType() constantly.
I'm attempting the following implementation:
Convert both 3, 2 and 1 to the desired unknown type. (This assumes a conversion from an int to the numeric type is possible, which should always be possible anyhow.)
In case 3 / 2 == 1, it is an integral type. Otherwise, it is a nonintegral type.
This solution doesn't rely anywhere on knowing the type and solely uses conversions and calculations.
This is probably trivial, but I can't think of a better way to do it. I have a COM object that returns a variant which becomes an object in C#. The only way I can get this into an int is
int test = int.Parse(string.Format("{0}", myobject))
Is there a cleaner way to do this? Thanks
You have several options:
(int) — Cast operator. Works if the object already is an integer at some level in the inheritance hierarchy or if there is an implicit conversion defined.
int.Parse()/int.TryParse() — For converting from a string of unknown format.
int.ParseExact()/int.TryParseExact() — For converting from a string in a specific format
Convert.ToInt32() — For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined.
as int? — Note the "?". The as operator is only for reference types, and so I used "?" to signify a Nullable<int>. The "as" operator works like Convert.To____(), but think TryParse() rather than Parse(): it returns null rather than throwing an exception if the conversion fails.
Of these, I would prefer (int) if the object really is just a boxed integer. Otherwise use Convert.ToInt32() in this case.
Note that this is a very general answer: I want to throw some attention to Darren Clark's response because I think it does a good job addressing the specifics here, but came in late and wasn't voted as well yet. He gets my vote for "accepted answer", anyway, for also recommending (int), for pointing out that if it fails (int)(short) might work instead, and for recommending you check your debugger to find out the actual runtime type.
The cast (int) myobject should just work.
If that gives you an invalid cast exception then it is probably because the variant type isn't VT_I4. My bet is that a variant with VT_I4 is converted into a boxed int, VT_I2 into a boxed short, etc.
When doing a cast on a boxed value type it is only valid to cast it to the type boxed.
Foe example, if the returned variant is actually a VT_I2 then (int) (short) myObject should work.
Easiest way to find out is to inspect the returned object and take a look at its type in the debugger. Also make sure that in the interop assembly you have the return value marked with MarshalAs(UnmanagedType.Struct)
Convert.ToInt32(myobject);
This will handle the case where myobject is null and return 0, instead of throwing an exception.
Use Int32.TryParse as follows.
int test;
bool result = Int32.TryParse(value, out test);
if (result)
{
Console.WriteLine("Sucess");
}
else
{
if (value == null) value = "";
Console.WriteLine("Failure");
}
Maybe Convert.ToInt32.
Watch out for exception, in both cases.
var intTried = Convert.ChangeType(myObject, typeof(int)) as int?;
I am listing the difference in each of the casting ways. What a particular type of casting handles and it doesn't?
// object to int
// does not handle null
// does not handle NAN ("102art54")
// convert value to integar
int intObj = (int)obj;
// handles only null or number
int? nullableIntObj = (int?)obj; // null
Nullable<int> nullableIntObj1 = (Nullable<int>)obj; // null
// best way for casting from object to nullable int
// handles null
// handles other datatypes gives null("sadfsdf") // result null
int? nullableIntObj2 = obj as int?;
// string to int
// does not handle null( throws exception)
// does not string NAN ("102art54") (throws exception)
// converts string to int ("26236")
// accepts string value
int iVal3 = int.Parse("10120"); // throws exception value cannot be null;
// handles null converts null to 0
// does not handle NAN ("102art54") (throws exception)
// converts obj to int ("26236")
int val4 = Convert.ToInt32("10120");
// handle null converts null to 0
// handle NAN ("101art54") converts null to 0
// convert string to int ("26236")
int number;
bool result = int.TryParse(value, out number);
if (result)
{
// converted value
}
else
{
// number o/p = 0
}
There's also TryParse.
From MSDN:
private static void TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
Strange, but the accepted answer seems wrong about the cast and the Convert in the mean that from my tests and reading the documentation too it should not take into account implicit or explicit operators.
So, if I have a variable of type object and the "boxed" class has some implicit operators defined they won't work.
Instead another simple way, but really performance costing is to cast before in dynamic.
(int)(dynamic)myObject.
You can try it in the Interactive window of VS.
public class Test
{
public static implicit operator int(Test v)
{
return 12;
}
}
(int)(object)new Test() //this will fail
Convert.ToInt32((object)new Test()) //this will fail
(int)(dynamic)(object)new Test() //this will pass
You can first cast object to string and then cast the string to int;
for example:
string str_myobject = myobject.ToString();
int int_myobject = int.Parse(str_myobject);
this worked for me.
int i = myObject.myField.CastTo<int>();
This worked for me, returning 0 also when myobject contains a DBNull
int i = myobject.ToString().Cast<int>().FirstOrDefault();