Linq Exception on cast [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a small piece of code to refactor. Someone wrote cast in such style:
list.OrderBy(u => (int)u.Original).First();
Sometimes this code throw Invalid Cast Exceptions (field Original is of type object).
Example:
list[0].Orginal = 200,
list[1].Orginal = 85
Everything is Ok.
list[0].Orginal = 275452,
list[1].Orginal = 154754
Throws Exception
Anyone know why?

Since it sometimes throws the invalid cast exception, it means you sometimes have non-int types of instances in your list. You can avoid them before casting, but this is not really a good type of a design I guess.
I would do as I show below as a quick fix.
list.Where(u => u.Original is int).OrderBy(u => (int)u.Original).First();
Then I would go ahead and check what am I missing as following:
list.Where(u => !(u.Original is int)).ForEach(u => Console.WriteLine(u.Original.GetType()))
Then fix the list beforehand.

As others suggested you should avoid the unnecessary cast. In your class simply change the type of Orginal from object to int and you won't need the cast in the LINQ query.

The code compiles and runs with no problem.
https://dotnetfiddle.net/dadrYJ
These are not the Datatypes you are looking for
What you actually meant was
https://dotnetfiddle.net/ygJTyU
list[0].Orginal = 2147483647;
list[1].Orginal = 154754;
where n > 0
Given that. The bug is pretty clear.
Refactor:
var value = int.MaxValue + n;
list[0].Orginal = value;
Refactor:
int64 value = int.MaxValue + n;
list[0].Orginal = value;
Therefore:
public int Lambda_OrderBy(Foo u)
{
return (int) u.Orginal;
}
Refactor:
public int Lambda_OrderBy(Foo u)
{
int64 value = u.Orginal;
return (int) value; // FAIL!
}

Related

Accessing a property through reflection returns a different value [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Ok, as my original question seemed a bit ambiguous because I was asking for a general question about the C# language, but showing part of a particular example where I was having a problem with it, I'm going to try to rewrite so that it is clearer that my question is about the C# language, not about my particular problem.
I currently have a property (several, in fact) of a class, that return a different value depending on whether you access them directly by code, or using reflection. This is what happens when I access the property using the immediate console of VS:
> SelectedLine.QtyOutstanding
0
> var prop = SelectedLine.GetType().GetProperty("QtyOutstanding")
> prop.GetValue(SelectedLine)
8
Regardless of how the property is defined, what is the difference, in C#, between both ways of accessing the property?
Shouldn't they both run exactly the same code in the setter/getter, if there is one?
(Considering that GetType() returns the same type as the variable is declared as)
I found a way to produce this, maybe your case looks like that?
If your SelectedLine is accessible via interface, and your class has an explicite implementation of that, but also has a public property with the same name, this could lead to different results.
Example
class Program
{
static void Main(string[] args)
{
var SelectedLine = (ILine)new Line(8);
Console.WriteLine(SelectedLine.QtyOutstanding); // 0
var prop = SelectedLine.GetType().GetProperty("QtyOutstanding");
Console.WriteLine(prop.GetValue(SelectedLine)); // 8
Console.ReadLine();
}
}
class Line : ILine
{
public Line(int qtyOutstanding)
{
QtyOutstanding = qtyOutstanding;
}
public int QtyOutstanding { get; }
int ILine.QtyOutstanding
{
get
{
return 0;
}
}
}
interface ILine
{
int QtyOutstanding { get; }
}

Why does char[].Cast<int> raise a cast exception? [duplicate]

This question already has answers here:
Why Enumerable.Cast raises an InvalidCastException?
(2 answers)
Closed 5 years ago.
Here is the code. It's simple enough.
var text = "abcdef";
var c1 = text.Cast<int>().ToArray(); // either this one
var c2 = text.ToCharArray().Cast<int>().ToArray(); // or this one
It raises an invalid cast exception in either case. Why?
For bonus marks, what's the simplest way to do what I'm obviously trying to do, if this is not it?
So, the code I'm actually going to write it this:
var c3 = text.Select(c=>(int)c).ToArray();
Which works fine.
Look at the source code of Cast. When you use Cast you are iterating the collection as an array of object, and then it is converted to the desidered type. So the generated code (for the Cast part) for the code you post is:
foreach (object item in text)
{
yield return (int)item;
}
Of course, this will generate an exception as documented here (link provided by Rawling in the comments, thank you).
To reproduce this you can try this code (you will get the same error):
var myChar = 'c';
object myObject = myChar;
int myInt = (int)myObject; // Exception here
A possibile solution
Disclaimer: tested only with the given example and of course really slow).
You could make your own Cast method using Convert.ChangeType.
public static class IEnumerableExtensions
{
public static IEnumerable<TResult> MyCast<TResult>(this IEnumerable source)
{
var type = typeof(TResult);
foreach (var item in source)
{
yield return (TResult)Convert.ChangeType(item, type);
}
}
}
Then you can use it as you would do with Cast.
var c1 = text.MyCast<int>();
I can't find where it is documented, but LINQ's Cast uses a cast via object, essentially performing
int i = (int)(object)c;
on each character in your string.
It boxes the char, and then tries to unbox it as an int, which isn't possible.
var text = "abcdef";
var intText = text.Select(c => (int)c);
This is something you can start with to convert each char to int in a form of IEnumerable.

How can I get the datatype of an array in C#? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am making a sort of statistical software that firstly needs to 'detect' the datatype of an array.
Firstly, X[,] is an array of sometype, can be all strings, all double, all ints or a combination of all.
Now, for every column X[] I need to know the datatype. Like:
If everything is 0 or 1, then Boolean (or binomial)
elseIf everything is integer, then integer
elseIf everything is double, then double
else: String
I need something like this in C#.
So it seems what you're trying to do here is find the "lowest common denominator" of types here. The most derived type that all of the items in the collection "are".
We'll start out with this helper method to get the entire type hierarchy of an object (including itself):
public static IEnumerable<Type> BaseClassHierarchy(object obj)
{
Type current = obj.GetType();
do
{
yield return current;
current = current.BaseType;
} while (current != null);
}
Now we can take a sequence of objects, map each to its hierarchy, intersect all of those sequences with each other, and then the first item of that result is the most derived type that is common to all of the other objects:
public static Type MostDerivedCommonType(IEnumerable<object> objects)
{
return objects.Select(o => BaseClassHierarchy(o))
.Aggregate((a,b)=> a.Intersect(b))
.First();
}
One simple idea is you can try to cast/parse as the different types and if that fails, move on to the next type. A very brief example of this is:
foreach (var element in myArray) {
double parsedDouble; int parsedInt;
var defaultValue = element.ToString();
if (Double.TryParse(defaultValue, out parsedDouble)) {
// you have something that can be used as a double (the value is in "parsedDouble")
} else if (Int32.TryParse(defaultValue, out parsedInt)){
// you have something that can be used as an integer (the value is in "parsedInt")
} else {
// you have something that can be used as an string (the value is in "defaultValue")
}
}
I believe that should probably get you started. Good luck!
Note
As other's have said - it is better to use strong types in C#. In most cases you can probably select a single type and use that rather than performing the checks above.

left hand side of an assignment must be a variable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Trying to put an integer data from database(Linq to sql) into a label getting this error exception:
left-hand side of an assignment must be a variable property or
indexer
Code:
protected void Page_Load(object sender, EventArgs e)
{
DataClassesDataContext data = new DataClassesDataContext();
var visit = (from v in data.SeeSites where v.Date == todaydate select v).FirstOrDefault();
int seennow = visit.See; // On This line I can put data in seenow variable, no problem
Convert.ToInt64(lblSeeNow.Text) = visit.See; // exception error appears here
}
Try:
if (visit.See != null) {
lblSeeNow.Text = visit.See.ToString();
}
You cannot assign something to a function result. In your case lblSeeNow.Text is of type String hence usage of ToString(); method of your Int value.
You need to use
lblSeeNow.Text = visit.See.ToString();
Convert.ToInt64(lblSeeNow.Text) = visit.See;
As you mentioned, this is the issue.
Convert.ToInt64 is a method. But you're trying to save a value to it.
You can't.
Just do this
lblSeeNow.Text = visit.See.ToString();
I think you want
lblSeeNow.Text = visit.See.ToString();
You can't assign anything to
Convert.ToInt64(lblSeeNow.Text)
because it evaluates to a number.
Convert.ToInt64(lblSeeNow.Text) isn't a variable. It takes the value in lblSeeNow.Text and converts it to a long. There isn't a variable to store stuff in anymore.
You probably want this:
lblSeeeNow.Text = visit.See.ToString();
You should convert the integer to string, also add a check for being sure that visit is not null
lblSeeNow.Text = visit != null ? visit.See.ToString() : string.Empty

Techniques to deal with "not all code paths return a value" when your algorithm already takes care of it [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In C#, sometimes there are code paths that don't return a value, and it is nice that the compiler errors out, and allows you to fix them. However there are times where there STRUCTURALLY is a place where it doesn't, but the ALOGIRTHM would prevent that structure from happening.
Here is a simple contrived example.
public static int test1(bool a)
{
if (a) return 1;
if (!a) return 2;
}
Of course people will tell me , that my "algorithm" is stupid and my second test is redundant and I should just do.
public static int test1(bool a)
{
if (a) return 1;
else return 2;
}
or even
public static int test1(bool a)
{
if (a) return 1;
return 2;
}
I purposely choose this simple "Redundant" example, rather than my real world algorithms, as I want to focus on this issue specifically, not about 10 different ways I could have written the algorithm :)
So what are the possible ways to deal with this, and what are the pro's and con's of each.
1) is what we just covered, and that's refactor the algorithm. Sometimes this may not be possible, or the end result may not be as per formant, easy to read/understand or maintain.
other is just to return something that would never happen, such as null.. but in this case i'm dealing with an integer and i'd have to put 0, which feels ever dirtier
public static int test1(bool a)
{
if (a) return 1;
if (!a) return 2;
//this code never happens, but i need to keep the compiler happy
return 0;
}
or use exceptions
public static int test1(bool a)
{
if (a) return 1;
if (!a) return 2;
throw new Exception("this code never happens, but i need to keep the compiler happy");
}
however every time I've dealt with this , no matter what technique I take i'm not happy with the result and feel a little dirty.
Are there alternatives?
Generally you throw Exceptions when there is an exceptional case... a bool not being true or false would be rather exceptional! I would throw an exception to keep the compiler happy, but also because you don't know how the method could change in the future.
I wouldn't consider an if ... else as dirty when dealing with a bool for exactly the reason that you use bools, they only have two values, when there are more possibilities (i.e. a string) then you can use more complex test.
When you have a compile error that all your code paths do not return a value, there is no flag to set or "trick," you have to either return a default value or throw an exception. I'm a firm believer in throwing an InvalidOperationException("Unexpected code reached, this method has been modified incorrectly").
Why it's not dirty: if someone else comes along and makes a change that causes your exception to be thrown, they'll know they did something that the author of the exception viewed as fundamentally wrong. Returning a default value could quietly break the consumers of the method, so it's good practice to use an exception as a safety net.
public static int test1(bool a)
{
return a ? 1 : 2;
}
Use a variable and assign the value to it and then return that value at the end of the function.
private bool isValid()
{
bool result = false;
try {
//some code
result = true;
} catch {
result = false;
}
return result;
}
Another option you might consider in this case is using the Debug.Fail() method.
public static int test1()
{
if (myComplexAlgo()) return 1;
if (myCatchAllAlgo()) return 2;
Debug.Fail("I should never be here!");
return -1;
}
It isn't a good fit for everyone, the advantage in this method is that you can use it to make sure your tests fail without possibly crashing your production code. This can (hopefully) catch future problems in the code in case your algorithm or conditions change.

Categories