Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I’m trying to do a cast that involves var. I have initialized my variable like this:
var updateContent = (MyType)null;
if (correctTime)
{
var getDataFromDatabase = from d in db.Content where d.someId == id select d;
//Here's where my I need to do some type of cast.
updateContent = getDataFromDatabase
}
Is there a correct cast that I can use to store getDataFromDatabase in updateContent?
UPDATE:
Sorry my questions was unclear. Based on all your comments I was able to accomplish the following:
IEnumerable<MtType> updateContent = null;
if (correctTime==true)
{
IEnumerable<MtType> getDataFromDatabase = var getDataFromDatabase = from d in db.Content where d.someId == id select d;
updateContent = getDataFromDatabase;
}
My final objective was to be able to access returns from inside an if block and this did the trick. Thanks again for all your help.
The result from you query will be an IEnumerable<Content>. If you want to load the results from your query into MyType then you need to do a projection like this:
var getDataFromDatabase = from d in db.Content where d.someId == id
select new MyType { Prop1 = d.Prop1, Prop2 = d.Prop2 };
This will give you an IQueryable<MyType>, which in turn inherits IEnumerable<MyType>, in getDataFromDatabase
If you just want to get the the first MyType from you query results, then you can do:
updateContent = getDataFromDatabase.FirstOrDefault();
The keyword var is just a handy abbreviation for the concrete type. It is not something like a dynamic type or so. As quite a lot of commentors stated before, the two following lines are identical
var myVar1 = (MyType)null;
MyType myVar2 = (MyType)null;
The only difference is that the typecast can be ommited in the second line. So, and this was mentioned as well, you are trying to assign an IEnumerable<OfSomeType> to a variable of MyType which simply does not and will never work.
Resharper's refactoring options allow you to switch between implicit (var) and explicit (MyType) declaration.
I assume that in the code following what you posted there's a check to see if updateContent is null.
This seems like a really good application of the conditional operator:
var updateContent = correctTime
? (from d in db.Content where d.someId == id select d)
: null;
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Is there any way to change a dynamic type property value ?
Code Example:
dynamic result = new { Status = "WARNING", Modified = false, Message = string.Empty };
result.Status = "OK";
Is that possible at all using C# ?
Thanks
Dynamic data type is added in c# 4.0. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.
Though, in most cases, dynamic data type behaves like an object.
In the abovementioned example:
You've created an anonymous type variable which is like the class type but it can only include public read-only members so you can't change result.Status value in this case.
TO SOLVE THE PROBLEM :
I think you should use generic collection like dictionary
The code may look like this:
var result = new Dictionary<string, object>() { {"Status", "Warning"}, {"Modified", false}, {"Message", string.empty} };
result ["Status"] = "Ok";
No this is not possible. You will get a runtime error telling you that the property Status of the anonymous type is write protected or read-only.
For future use here is the online compiler proof:
The documentation says:
Anonymous types contain one or more public read-only properties.
You would need to recreate the object again using the values from the original one for the rest of the properties:
var result = new { Status = "WARNING", Modified = false, Message = string.Empty };
result = new { Status = "OK", Modified = result.Modified, Message = result.Message };
Console.WriteLine(result.Status);
Output:
OK
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 4 years ago.
Improve this question
I have an object obj1 with 11 properties.
Is it better to do this
Obj obj1 = new Obj()
{
prop1 = int.Parse(data.Rows[0]["RequestId"].ToString())
prop2 = IsBoss = (bool)data.Rows[0]["IsBoss"]
///etc...
}
or should I do
{
Obj obj1 = new Obj(){}
obj1.prop1 = int.Parse(data.Rows[0]["RequestId"].ToString())
obj1.prop2 = IsBoss = (bool)data.Rows[0]["IsBoss"]
///etc...
}
Also as a side question, when my data rows are null, an exception "Input string was not in a correct format" gets thrown because the field from the database is null. Typically the data wouldnt be null but would it be best to use a ternary operator to check if null or should i do a case in the sql qry.
Like the other answers, how you instantiate an object is up to you. Personally, I used to instantiate them and assign the properties all in one statement. The issue that I kept running into is when a had a property that failed to make it back from the database (like your null exception scenario), the the exception wouldn't give me an accurate line number. For that reason, I've moved to instantiating the object, then assigning the properties. This way, you'll know exactly which line/property is causing the issue.
MyClass obj = new MyClass();
obj.PropertyOne = "";
obj.PropertyTwo = "";
//etc...
As far as your second question goes, I handle nulls by using a ternary in combination with the IsDBNull() method on the DataTableReader.
MyClass obj = new MyClass();
obj.PropertyOne = rdr.IsDBNull(rdr.GetOrdinal("RequestId")) ? 0
: rdr.GetInt32(rdr.GetOrdinal("RequestId"));
I prefer setting object properties on initialization as per the first example, I think the code looks cleaner and better contained, but that is more of a personal preference.
For your second question when data is null coming back from the database you've got a few options.
{
var obj1 = new Obj()
{
prop1 = int.TryParse(data.Rows[0]["RequestId"]?.ToString(), out int val) ? val : -1,
prop2 = IsBoss = bool.TryParse(data.Rows[0]["IsBoss"].ToString(), out bool isBoss) ? isBoss : false
}
}
Haven't tested but something like that should work, but it's not clean. I'd separate out the parsing into its own method or block. To help the code breathe a little.
Something like this:
{
if(!(int.TryParse(data.Rows[0]["RequestId"]?.ToString(), out int requestId)))
{
requestId = -1;
}
bool.TryParse(data.Rows[0]["IsBoss"]?.ToString(), out IsBoss);
var obj1 = new Obj()
{
prop1 = requestId,
prop2 = IsBoss
}
}
This question already has answers here:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>
(5 answers)
Closed 5 years ago.
I am getting following error
Cannot implicitly convert type
'System.Collections.Generic.List<AnonymousType#1>' to
'System.Collections.Generic.List<string>'
I tried reading similar questions on stack overflow but didn't find a solution.
My code is as below
var head =
from key in doc.Descendants("Header").Descendants("Article")
select new
{
value = (key.Value == String.Empty ?
from q in doc.Descendants("Header").Descendants("Article") select q.Value : from a in doc.Descendants("Header").Descendants("Article")
select a.Attribute("DefaultValue").Value)
};
List<string> hsourceFields = head.ToList();
If the value of xml node is empty I am reading the default value specified for that xml node
<Header>
<Article>News</Article>
<Article DefaultValue ="Sport"></Article>
</Header>
I want to be able to return a List which I am not able to by getting the error.
Looks like your code was getting a List<AnonType{value = List<string>}> instead of a List<string>
I think you want something like this that will select the text from an article or if that is empty it will take the value of the DefaultValue attribute. Note this doesn't handle when there is no text and no attribute.
var head =
from key in doc.Descendants("Header").Descendants("Article")
select
string.IsNullOrEmpty(key.Value) ?
key.Attribute("DefaultValue").Value :
key.Value;
List<string> hsourceFields = head.ToList();
Or a slightly abbreviated version that uses xpath and method chains
var hsourceFields = doc.XPathSelectElements("/Header/Article")
.Select (x => string.IsNullOrEmpty(x.Value) ?
x.Attribute("DefaultValue").Value :
x.Value).ToList()
If you read the error it exactly tells you the problem. You want a string list however you have a list of anonymous objects. Instead use
var hSouceFields = head.ToList()
I changed the way I was reading xml nodes to
var head = (from k in doc.Descendants("Header")
select k).ToList();
List<String> hsourceFields = new List<string>();
foreach (var t in head.Descendants("Article"))
{
if (t.Attribute("DefaultValue") != null)
{
hsourceFields.Add(t.Attribute("DefaultValue").Value);
}
else
hsourceFields.Add(t.Value);
}
Not proud of my solution though.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have an object named 'Account' and the following code:
Account objAcc = new Account();
objAcc.Name = "Test";
The above is working fine, as expected. I now have a list of values as follows:
string props = "Name,Address,Telephone";
Now, what I want to do is see if "Name" exists in that list. I only have the object to use though (hard coding a case statement etc isn't possible as the object is dynamic), so from objAcc.Name, I somehow need to get "Name" from that, and then see if it's in the list.
Thanks in advance, I hope it's clear enough,
Dave
You can use reflection, by doing that :
var properties = objAcc.GetType().GetProperties();
foreach(var property in properties)
{
if(props.Contains(property.Name))
{
//Do you stuff
}
}
string test = objAcc.GetType().GetProperty("Name") == null ? "" : objAcc.GetType().GetProperty("Name").Name;
bool result = "Name,Address,Telephone".Split(',').Contains(test);
You may use the following method if you like:
public bool PropertyExists<T>(string propertyName, IEnumerable<string> propertyList,T obj)
{
string test = obj.GetType().GetProperty(propertyName) == null ? "" : obj.GetType().GetProperty(propertyName).Name;
bool result = propertyList.Contains(test);
return result;
}
Giannis
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Use of var keyword in C#
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?
For example I rather lazily used var in questionable circumstances, e.g.:-
foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.
More legitimate uses of var are as follows:-
var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.
Interestingly LINQ seems to be a bit of a grey area, e.g.:-
var results = from r in dataContext.SomeTable
select r; // Not *entirely clear* what results will be here.
It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.
It's even worse when it comes to LINQ to objects, e.g.:-
var results = from item in someList
where item != 3
select item;
This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.
There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.
Personally I find the circumstances you describe far from questionable, since there is no point in repeating yourself unless you specifically want the static type of a variable to be different than the static type of the expression used to initialize the variable. For example:
IEnumerable<int> foo = new List<int>(); // It's IEnumerable on purpose
Furthermore, there are absolutely no type safety concerns with var. The point is not that the variable can be of "any" type. It is of a very specific type, but you simply do not care to spell that type out.
I'm only using it as a place holder until I'm sure which datatypes I'm using.
Sure this is a short answer but I think it's pretty close that when you should use the var keyword.
the var keyword is used as shorthand in the language, but isn't a .NET type. The compiler must know the type of the variable to use the var keyword - so it is type-safe.
I personally only use it if the type name is also used in the assignment and the name is possible too long to duplicate in the code.
var dictionary = new Dictionary<string, string>();
It is also used for anonymous types (but still, the compiler must know the signature of the anonymous type).
var fred = new { Age = 23, Name = "Fred" };
This method is used commonly in the select clause of LINQ queries.
Just an "abstraction" or "syntax sugar" to be able to write a code without specifying first the type (this is no your first cases)
In second case: LINQ queries, instead, to rapresent some unknown, dynamic, not concrete, if you wish, type.
could be:
var results = from item in someList
where item != 3
select item; //item a class instance
could be
var results = from item in someList
where item != 3
select item.ItemName; //string property of that class
could be
var results = from item in someList
where item != 3
select new {item.ItemName, item.ID}; //unknown type dynamically generated, that conains the string and integer, like result
As far as I know var remains strong typed. The compiler calculated what the proper type should be. In fact it has no real meaning.
It is only a trick to reduce the number of manipulations. For instance when you change a type in one class, this can result in a cascade of modification. But its only a way to migrate work from the programmer to the compiler.
For instance your Linq query will result in a type IEnumerable<TA>. When you change some class so the result will be IEnumerable<TB> there is no need to change this part of the code.