Helper class to achieve common task - c#

I would like to create a helper class to do some common task.
For example, I am retrieving some results from Database and then assigning the values to variables. But some of the fields in my records might contain null as well. I would like to check before assigning that the value does not contain any null.
Also there are some variable those are type int, so like to check before parsing to the specific type.
int iValue=int.parse(Helpers.IsNull(dr[colName].toString()));
string strValue=Helpers.IsNull(dr[colName].toString());
How should I create a helper class and what value should I return with IsNull method?
Little confuse..
Thanks

Well what you are trying to acchieve is to avoid the NullReferenceException i guess.
You could achieve this by writing a generic method like this
public static TValue GetValueSafe<TValue,TObject>(TObject obj, Func<TObject,TValue> accessor)
{
if(obj== null)
return default(TValue);
return accessor(obj);
}
Then use it like this:
string strValue = Helpers.GetValueSafe(dr[colName], o => o.toString());
This would either return the value of toString, or if dr[colName] == null returns default(string) which is null.
You could exand this by adding a defaultParameter to define a value on "failure".
However i would'nt recommend using this.

A more radical approach (which would remove the issue) would be to eradicate NULLs from your values altogether.
The simplest way would be through ISNULL() when you query your database:
Where now you do
SELECT MyColumn FROM MyTable
You instead go
SELECT ISNULL(MyColumn, '') AS MyColumn FROM MyTable
Then you can assume no NULLs will get through to your code.

Related

Nullable record structs in C# [duplicate]

So I've got a collection of structs (it's actually a WCF datacontract but I'm presuming this has no bearing here).
List<OptionalExtra> OptionalExtras;
OptionalExtra is a struct.
public partial struct OptionalExtra
Now I'm running the below statement:
OptionalExtra multiOptExtra = OptionalExtras.Where(w => w.Code == optExtra.Code).FirstOrDefault();
if (multiOptExtra != null)
{
}
Now this won't compile:
the operator != cannot be applied to opperands of type OptionalExtra
and '<null>'
After a little googling I realised it's because OptionalExtra is a struct. Which I believe is not nullable unless defined as a nullable type?
So my question is, if my where statement returns no results what will be the outcome of the FirstOrDefault call? Will it thrown an exception?
Incidently this should never happen but better safe than sorry.
If your collection is empty, FirstOrDefault will return default(OptionalExtras). The default value of a struct is the struct with all its values in turn default initialized (i.e. zero, null, etc.).
If you assume that there will be an element and your code doesn't work with an empty collection, Use First() instead, since that will throw an exception when your collection is empty. It's generally better to fail fast than to return wrong data.
If you cannot assume that there will be an element, but also cannot deal with struct default initialization, you might make the structs in the collection a nullable value type, for example as follows:
OptionalExtras
.Where(w => w.Code == optExtra.Code)
.Cast<OptionalExtra?>()
.FirstOrDefault();
This way you can get a null return even for a struct. The key idea here is to extend the set of possible values to include something other than an OptionalExtra to allow detection of an empty list. If you don't like nullables, you could instead use a Maybe<> implementation (not a .NET builtin), or use an empty-or-singleton list (e.g. .Take(1).ToArray(). However, a nullable struct is likely your best bet.
TL;DR;
.FirstOrDefault<T>() returns default(T) if the sequence is empty
Use .First() instead if you assume the list is non-empty.
Cast to nullable and then use .FirstOrDefault<T>() when you cannot assume the list is non-empty.
As others have said, the result of your code when no elements match will be:
default( OptionalExtra )
If you want a null returned, you can cast your list to OptionalExtra?
OptionalExtra? multiOptExtra = OptionalExtras.Cast<OptionalExtra?>().Where( ...
You can then test for null
If default(OptionExtra) is still a valid value, it's better to change your code to this
var results = OptionalExtras.Where(w => w.Code == optExtra.Code).Take(1).ToList();
if (results.Any()) {
multiOptExtra = results[0]
}
The result will be the default value of your struct, e.g. default(OptionalExtras).
Whereas for a reference type the default value is null.
its provide you defualt value for your structure like as below
int[] numbers = { };
int first = numbers.FirstOrDefault();
Console.WriteLine(first);//this print 0 as output
other option to handle is make use of default value like as below
List<int> months = new List<int> { };
// Setting the default value to 1 by using DefaultIfEmpty() in the query.
int firstMonth2 = months.DefaultIfEmpty(1).First();
Console.WriteLine("The value of the firstMonth2 variable is {0}", firstMonth2);
If you want to check for null, use System.Nullable collection:
var OptionalExtras = new List<OptionalExtra?>();
/* Add some values */
var extras = OptionalExtras.FirstOrDefault(oe => oe.Value.Code == "code");
if (extras != null)
{
Console.WriteLine(extras.Value.Code);
}
Note that you have to use Value to access the element.
Assuming Code is a string for the purposes of my answer, you should be able just to test that value for its default.
OptionalExtra multiOptExtra = OptionalExtras.Where(w => w.Code == optExtra.Code).FirstOrDefault();
if (multiOptExtra.Code != null)
{
}

safe way to read from SqlDataReader [duplicate]

I am new to C#. I was executing some select queries from database tables using System.Data.SqlClient classes. I got sqlnullvalueexception while executing some select query. On googling I come to know that if the value is null in the database, SqlDataReader.GetString (or it's variants) will throw sqlnullvalueexception.
What is the best coding practice for this?
if (!sqlDataReader.IsDBNull(n)) value = r.GetString(n);
Any better way of coding?
If you don't want to repeat this a lot, just create a helper function, like this:
public static class DataReaderExtensions
{
public static string GetStringOrNull(this IDataReader reader, int ordinal)
{
return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
}
public static string GetStringOrNull(this IDataReader reader, string columnName)
{
return reader.GetStringOrNull(reader.GetOrdinal(columnName));
}
}
Which you can call like this:
value = reader.GetStringOrNull(n);
The code you posted is fine. You could also do something like that :
value = r[n] as string;
If the value in the database is null, r[n] will return DBNull.Value, and the cast to string will return null.
That really is the best way to go about it if you wish to avoid any exceptions. You need to decide whether or not a null field represents an exceptional situation in your code - if it doesn't then use this method. If it does then I would suggest that you either allow the exception to be thrown or catch the exception and wrap it in a more meaniful exception and throw that one.
But the main thing to know is that this is the standard way to retrieve values from a data reader when a null field does not represent an exceptional situation in the application domain.
This worked for me:
value = reader.GetValue(n).ToString();

Get data which is not `null` [duplicate]

I am new to C#. I was executing some select queries from database tables using System.Data.SqlClient classes. I got sqlnullvalueexception while executing some select query. On googling I come to know that if the value is null in the database, SqlDataReader.GetString (or it's variants) will throw sqlnullvalueexception.
What is the best coding practice for this?
if (!sqlDataReader.IsDBNull(n)) value = r.GetString(n);
Any better way of coding?
If you don't want to repeat this a lot, just create a helper function, like this:
public static class DataReaderExtensions
{
public static string GetStringOrNull(this IDataReader reader, int ordinal)
{
return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
}
public static string GetStringOrNull(this IDataReader reader, string columnName)
{
return reader.GetStringOrNull(reader.GetOrdinal(columnName));
}
}
Which you can call like this:
value = reader.GetStringOrNull(n);
The code you posted is fine. You could also do something like that :
value = r[n] as string;
If the value in the database is null, r[n] will return DBNull.Value, and the cast to string will return null.
That really is the best way to go about it if you wish to avoid any exceptions. You need to decide whether or not a null field represents an exceptional situation in your code - if it doesn't then use this method. If it does then I would suggest that you either allow the exception to be thrown or catch the exception and wrap it in a more meaniful exception and throw that one.
But the main thing to know is that this is the standard way to retrieve values from a data reader when a null field does not represent an exceptional situation in the application domain.
This worked for me:
value = reader.GetValue(n).ToString();

return a List< Id:int, Name:string>

I am having a function which return a list of type: List< Id:Name, Name:string >
how do you do specify in C# to return this List Type ?
Here is the code:
public ?????? GetDepartements( int idRegion )
{
var a = (from o in _meilleurPrestaEntities.Departements
where o.de_id_region == idRegion
select new {Id = o.id_departement, Name = o.nom}).ToList();
return a;
}
the return is used as Json result.
thanks
I'd suggest using a key value pair
return List<KeyValuePair<int,string>>()
[Edit] You'll need to modify your code slightly - it should look something like this:
var a = (from o in _meilleurPrestaEntities.Departements
where o.de_id_region == idRegion
select new KeyValuePair<int,string>(o.id_departement,o.nom}).ToList();
You can't. You have a list of anonymous type and you can't specify anonymous type as part of a method return type (or pretty much anywhere else, unless you can use var).
To fix this, you have several options:
Create normal class to represent the return type and use that in your return type.
Use something like List<Tuple<int, string>>.
Return List<dynamic>. This way, you will be able to treat the returned value as usual, but you will get no compile-time checking or IntelliSense.
Return List<object>. This can be useful if you don't need to access the properties in the usual way, but you will only pass the result to something that uses reflection.
I think you have to specify a type and then use that type for your return value and in your select statement.
I don't have VisualStudio open to try it, but I think you can actually return dynamic in this case. Or you could use ExpandoObject.
However, as others have mentioned, the "better" way is to use something like Tuple or KeyValuePair, or don't be lazy and just make an actual model for what you will return to the view (in other words, a "View Model").

SqlDataReader.GetString and sqlnullvalueexception

I am new to C#. I was executing some select queries from database tables using System.Data.SqlClient classes. I got sqlnullvalueexception while executing some select query. On googling I come to know that if the value is null in the database, SqlDataReader.GetString (or it's variants) will throw sqlnullvalueexception.
What is the best coding practice for this?
if (!sqlDataReader.IsDBNull(n)) value = r.GetString(n);
Any better way of coding?
If you don't want to repeat this a lot, just create a helper function, like this:
public static class DataReaderExtensions
{
public static string GetStringOrNull(this IDataReader reader, int ordinal)
{
return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
}
public static string GetStringOrNull(this IDataReader reader, string columnName)
{
return reader.GetStringOrNull(reader.GetOrdinal(columnName));
}
}
Which you can call like this:
value = reader.GetStringOrNull(n);
The code you posted is fine. You could also do something like that :
value = r[n] as string;
If the value in the database is null, r[n] will return DBNull.Value, and the cast to string will return null.
That really is the best way to go about it if you wish to avoid any exceptions. You need to decide whether or not a null field represents an exceptional situation in your code - if it doesn't then use this method. If it does then I would suggest that you either allow the exception to be thrown or catch the exception and wrap it in a more meaniful exception and throw that one.
But the main thing to know is that this is the standard way to retrieve values from a data reader when a null field does not represent an exceptional situation in the application domain.
This worked for me:
value = reader.GetValue(n).ToString();

Categories

Resources