What is the name of this c# shorthand? - c#

I have seen the below code. I understand what it's doing. It gets a list of enum and then matches it with value passed and returns the matched one. What is this shorthand called? Is there a link a to more advanced short hands like this?
string a = null;
a = getListOfEnums()["matching value"];
Edit
It does not need to be an enum. It can be a dictionary object (key value pair) too.

Are you sure about the code? In current form the only way it may work is that getListOfEnums() returns a delegate that takes a string and returns a string. That wouldn't match name of the method, so I don't think that's the case.
What I think you're talking about is indexer:
string a = null;
a = getListOfEnums()["matching value"];

Related

How to make a method that makes a string null

I want to make a method that gives a string (input in method) the value null. This is for my database, so that there are no 'open' values.
It needs to be something like this:
public string NulValue (string value)
{
value = null; //the string-value needs to get the value null here
return value; //returning the value
}
But this is not giving the string the value null. I think the solution is very easy, but I don't get it to work. I use WPF.
Here is where I want to use the method:
string checkcomment = TextBxComment.Text;
if (checkcomment == "")
{
NulValue(checkcomment);
}
You can not make a string anything. While strings are reference types, they are on that is designed to work like Value Type for many purposes. Do not try to learn class semantics with string. You can however set the reference to null, wich works similar to setting a value type to anything in a function.
By default functions use "call by value", wich means a copy of the Primitive Type or Reference variable is made. And you then work with that copy. In order to force a function to use call by reference (in wich the actually variable is re-used and can be modified), the ref and out keywords are used for that.
However teh whole operation makes little sense. As far as you example code shows, you want to set the reference variable to null. At wich point
myValue = null;
will always be easier to write and read then
NullValue(ref myValue);
But of course there might be some logic you have not shown us.
Properties can not be used as ref values. So if you use properties, you have to write somewhat more code.:
var temp = Instance.MyValue;
NullValue(ref temp);
Instance.MyValue = temp;
With a Database, this might be about mapping the .NET Type/Value Null to the Databases Type/value Null. Wich can be very different things.

Best way to cast/convert number to string

I was looking at the following question, comparing casting to converting, which basically stated (Through all the answers), that if you know your object is a string, use (string) rather than .ToString().
That got me thinking - what if your object might be a string or int? Or does knowing its a string also extend to integers?
Would this rule apply to a byte too? (Accidently used bit earlier)
Edit
This answer shows many ways of converting an integer to a string, but that still doesn't explain which to really use.
Specifically, casting a number to a string presents no real issue, as any number can be expressed as a string (Important: not every string, however, can be expressed as an number! e.g. how would you express "banana" as a number?)
string mystring = mynumber.ToString();
works everytime, without fail (assuming non-null values in case you're using nullable types).
The same exact method applies for any primitive type, and some others (DateTime, StringBuilder, ...)
It's the conversion from string to number that can be problematic. Usually not the other way around.
Edit if you want to take advantage of direct (string) casting in case your starting object is already a string, maybe this can help?
string mystring = (myobject as string) ?? myobject.ToString();
myobject as string will try to directly cast the object to a string. If it fails, that returns null.
?? myobject.ToString() then makes sure that, in case the previous attempts resulted in null, the regular .ToString() method is called as a fallback scenario.
If you have an object which is of type int but is boxed as an object, you cast it back:
object myBoxedStr = "stringvalue";
string unboxedStr = (string)myBoxedStr;
http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
If you have a string which contains an int value, you parse (or tryparse) it
string myIntStr = "5";
int myInt = int.Parse(myIntStr);
If you don't know if the boxed type is the assummed type you use is and as
object assumedMyType = new MyType();
MyType myType = assumedMyType as MyType;
the as keyword returns null if the conversion has failed (rather than throwing an exception)
With the is keyword you can check if the assumed type is of the correct type before converting it
object assumedInt = 5;
if(assumedInt is int)
{
int myInt = (int)assumedInt;
}
The takeaway from that question is that if you know that your value is actually of the type you want, then you should cast it (e.g. (int)). This has several benefits: it is efficient, it clearly expresses your intent, and it will fail conspicuously if your presumption is false.
You use other sorts of conversions when you don't know that the value of the type you want, or when you know that it is not. For instance, if you have an array of strings, you should not use (int), but rather ParseInt and its ilk. If you have an array of objects, some of which are ints, then the as operator might be what you want.
string name = GetSql["username"].ToString();
This code running slow. Because object(object, int, double etc.) to string converting operations.
string name = (string)GetSql["username"];
This code very fast running. Because not converting operations only type designation.
int to string convert.
1-)
var number = 0;
int.TryParse("213", out number);
It is better to TryParse method because it can block error occurs.
2-)
var number = int.Parse("123");
I think that the best option, if you strongly suspect that it's a string, but not actually sure, is something like this:
string valueString = value is string ? (string) value : (value ?? string.Empty).ToString();
My experience is that best cast/convert is archived through Convert class. That's the way C# expecting from you. That class care about all that ugly things that would you normally do.
When you do type conversion or simply typecasting, it even round float to int.

What alternative approach could be used in C# to avoid method returning `object` type?

I know that the method is returning List<string> at the moment. But in some (which occur quite frequently in our application) scenarios, it returns List having only one string.
So eventually it would return either string or List<string>.
Since it's unpredictable what it'll return at run time, at present it's return type is kept as object.
What alternative approach could be used to avoid method returning object?
EDIT:
I would like to have answer to the question What alternative approach could be used to avoid method returning object? ; without considering the scenario I described. List is enough here.
why return a string? a List<string> with a single string in it is perfectly well defined... use that! An ambiguous API is silly here.
Another option might be IEnumerable<string>, but... meh, just return the list with a single string!
Return a List that contains one or more string elements, and process the list as a list regardless of the number of elements it contains.
There is no problem to have a List with one and more and even with no string(empty list).
Why you want to have string when there is only one element in the List.
Just keep the API more clear.
I dont see the the problem of returning List<string> even the List contain only one element. But if you really want your method to behave differently with one string value, you could do
public List<string> GetStrList(out string val)
{
//set str = string.Empty; when value is more than one
//set str = whateverstring when value is only one
}
Hmm, does this method perhaps call 2 different methods inside its body, one returning a string and one returning a List<string>? If so, maybe you could change your method to return an IEnumerable<string>, and change the return GetSingleString(); statement to yield returnGetSingleString();
Or you could add it to a list with a single element and return the list, like some of the other answers suggest here

Casting vs Converting an object toString, when object really is a string

This isn't really an issue, however I am curious. When I save a string in lets say an DataRow, it is cast to Object. When I want to use it, I have to cast it ToString. As far as I know there are several ways of doing this, first is
string name = (string)DataRowObject["name"]; //valid since I know it's a string
and another one is:
string name = DataRowObject["name"].ToString();
I am interested in what is the difference between both? Is the first more efficient? (This is just a speculation, in my head ToString() method is implemented by some looping mechanism where just casting it "could" be faster, however this is just a "gut feeling" I have).
Is there even a faster / more elegant way of doing this?
Can anyone clear this up for me?
The two are intended for different
purposes. The ToString method of any
object is supposed to return a string
representation of that object. Casting
is quite different, and the 'as' key
word performs a conditional cast, as
has been said. The 'as' key word
basically says "get me a reference of
this type to that object if that
object is this type" while ToString
says "get me a string representation
of that object". The result may be the
same in some cases but the two should
never be considered interchangeable
because, as I said, they exist for
different purposes. If your intention
is to cast then you should always use
a cast, NOT ToString.
from http://www.codeguru.com/forum/showthread.php?t=443873
see also http://bytes.com/groups/net-c/225365-tostring-string-cast
If you know it is a String then by all means cast it to a String. Casting your object is going to be faster than calling a virtual method.
Edit: Here are the results of some benchmarking:
============ Casting vs. virtual method ============
cast 29.884 1.00
tos 33.734 1.13
I used Jon Skeet's BenchmarkHelper like this:
using System;
using BenchmarkHelper;
class Program
{
static void Main()
{
Object input = "Foo";
String output = "Foo";
var results
= TestSuite.Create("Casting vs. virtual method", input, output)
.Add(cast)
.Add(tos)
.RunTests()
.ScaleByBest(ScalingMode.VaryDuration);
results.Display(ResultColumns.NameAndDuration | ResultColumns.Score,
results.FindBest());
}
static String cast(Object o)
{
return (String)o;
}
static String tos(Object o)
{
return o.ToString();
}
}
So it appears that casting is in fact slightly faster than calling ToString().
Basically in your case it is better to leave type cast because .ToString() may hide bugs. For example, your data base schema changed and name is no longer of string type but with .ToString() your code still works. So in this case it is better to use type cast.
Here is implementation of String.ToString() - nothing special =)
public override string ToString()
{
return this;
}
Downcasting is a relatively slow operation since CLR has to perform various runtime type-checks. However, in this particular scenario casting to string is more appropriate than calling ToString() for the sake of consistency (you can't call ToInt32 on object, but cast it to int) and maintanability.
I want to make one more comment
If you are going to use casting: string name = (string)DataRowObject["name"]
you will get an Exception: Unable to cast object of type 'System.DBNull' to type'System.String' in case if the record in the database table has null value.
In this scenario you have to use: string name = DataRowObject["name"].ToString() or
You have to check for null value like
if(!string.IsNullOrEmpty(DataRowObject["name"].ToString()))
{
string name = (string)DataRowObject["name"];
}
else
{
//i.e Write error to the log file
string error = "The database table has a null value";
}
For data object, I suggest you to use "as" keyword like the following code.
string name = DataRowObject["name"] as string;
Please check it before you use value.
if(name != null)
{
// statement for empty string or it has value
}
else
{
// statement for no data in this object.
}
In this case:
string name = DataRowObject["name"].ToString();
since it is a string, I think that the ToString() method of a string object is simple as:
return this;
so IMHO there is no performance penalty.
PS
I'm a Java programmer, so this anwser is only a guess.
ToString() does not perform a cast by default. Its purpose is to return a string that represents the type (e.g. "System.Object").
If you want to avoid casting you could try to think of an implementation that is strongly typed (using generics, for example) and avoids DataRowObject altogether.
I know you mentioned that the Object is a string, but incase you're afraid that the returned object is null, you can also cast using "Convert.ToString(DataRowObject["name"]);" This has the added benefit of returning an empty string (string.empty) if the object is null, to avoid any null reference exceptions (unless of course you want an exception thrown in such cases).

How to tell what is passed when no value exists

For this code, how do you know that null is returned if there is no value in the querystring?
HttpContext context = HttpContext.Current;
string strValue = context.Request[name];
I'm asking because I never know what's being returned in many cases in the .NET framework when you don't get the value expected when it does not exist.
so if context.Request[name]; is called and the name doesn't exist in the querystring, how do you know it returns null or an empty string so that I can properly handle the case where it does not exist?
Use String.IsNullOrEmpty() to check for a Null or Empty string.:
string strValue = !String.IsNullOrEmpty(context.Request[name]) ??
context.Request[name] : "Some Default Value";
Or if you don't have a default value you'd like to set, you can do the check later:
if(String.IsNullOrEmpty(strValue))
{
// It's Null Or Empty
}
else
{
// It's Not
}
Update
Just saw the comment. If you're trying to figure out if referencing a key that doesn't exist in the Params collection (which is what you're using via shorthand), then check the MSDN documentation.
In this case, Params is a System.Collections.Specialized.NavmeValueCollection. The documentation is here. According to the documentation, a null value is indeed returned when a key is not found in the collection.
Therefore you don't have to use String.IsNullOrEmpty(). You could just:
string strValue = context.Request[name] ?? "Some Default Value";
If you want to set a default, or check for null otherwise.
As #Justin Niessner says, you can check the context.Request[name] for null as you read it. This is perfectly efficient and reasonable.
If you feel uncomfortable working with nulls, you can examine the collection into which name is the index.
In your example, context.Request[name] is shorthand for context.Request.Params[name]. Params is a NameValueCollection, which in turn has a property AllKeys. Assuming we're using .NET 3.5 you can then use .Contains() like so:
if (context.Request.Params.AllKeys.Contains(name))
{
// do something
}
Also, you specifically mention you're interested in the query string. context.Request[] returns not just the query string, but also Cookies, Form and ServerVariables. For the query string, use
if (context.Request.QueryString.AllKeys.Contains(name))
{
// do something
}
I think what you are asking is 'how do I know what the behaviour of this object is?' - in which case I don't know of a better answer than 'check the documentation' - in this case, HttpContext.Request is documented as being of type HttpRequest, which in turn is documented as having an Item method for which the documentation says:
If the specified key is not found, then a null reference (Nothing in Visual Basic) is returned.
What I can't immediately see is how you would light on the Item method specifically as the name of the indexer (this[]) method if you didn't know that that was a standard convention...
Request.Params is a NameValueCollection, which will return 'null' if a key does not exist in the collection.
So, if the URL was:
http://localhost
Then context.Request.Params["foo"] would be null.
Now, if the request was:
http://localhost?foo=
Then context.Request.Params["foo"] would be "".
I think this is what you are looking for.
You can do something like this using Extension Methods:
if(!Request["Name"].IsNullOrEmpty())
{
// do something with the Request["Name"] value
// OR
// You can extract the Request["Name"] into a variable and do the same with the variable
}
The ExtentionMethod look something like this:
public static bool IsNullOrEmpty(this string str)
{
return String.IsNullOrEmpty(str);
}
Thanks!

Categories