Incorrect Format

 

Here's the scenario: I'm building a basic 3-layer Web application for a client with business and data layers. Queries are performed in stored procedures, just basic ADO.NET. The table I am attempting to insert a record into has a range a field types such as strings, ints, decimals, etc.

If the user is entering integer or decimal values via texboxes, which is usually the case, then you have to expect either no data or a string of possibly mal-formed data. You must filter out the mal-formed data with validation and/or convert the resulting input data to the expected database type.

If you have a database field called SquareFeet of type int and you attempt to insert the following in your code-behind insert method, you will probably see this error:

// Results in error message
AddSomething(int squareFeet)
{
    Convert.ToInt32(SquareFeetTxtBox.Text.Trim());   
}

 

You must be careful if you are trying to fetch, say, an int or decimal as input:

// Correct way if SquareFeet field is an int
int squareFeet
if (int.TryParse(squareFeetTxt.Text.Trim(), out squareFeet))
    squareFeet = Convert.ToInt32(squareFeetTxt.Text.Trim());
else
     squareFeet = 0;
// Now insert the value as part of the record

 

// Correct way if SquareFeet field is a decimal
int squareFeet
if (decimal.TryParse(squareFeetTxt.Text.Trim(), out squareFeet))
    squareFeet = Convert.ToDecimal(squareFeetTxt.Text.Trim());
else
     squareFeet = 0.0m;
// Now insert the value as part of the record

 

References

Refer to these links for the differences between Convert.ToInt, int.Parse and Int.TryParse:
http://dotnetperls.com/int-parse-conversion
http://dotnetperls.com/int-tryparse

Refer to this link for an explanation of the 0.0m decimal syntax:
http://msdn.microsoft.com/en-us/library/364x0z75(VS.80).aspx

Moral of the Story
If you are learning any language, your first priority must be to understand the types thoroughly. Resist the temptation to gloss over the grammar just to get to the fancy stuff! :-)

kick it on DotNetKicks.com

Tags: , ,

ASP.NET | C#




C# 4.0 is the next version of the C# language being shipped with VS 2010. Personally, I'm still coming to terms with Generics as introduced in C# 2.0 and LINQ which came with 3.0. Anders Hejlsberg touched on the Covariance/Contravariance topic in his TechEd presentation in LA last month entitled "The Future of C#".

Evolution of C# - Anders Hejlsberg

 

The terms Invariance, Covariance and Contravariance are not by any means new. Anyone coming from a computer science background will have encountered the terms. Prior to attending Anders' session, I hadn't given this much conscious thought in a long time - we tend to know what we can and can't do within the syntactical constraints of a language - and tend not to question things further. However, in C# 4.0, delegates and interfaces will play nicer when working with generics. So much attention is likely to be focused on the dynamic programming additions in C# 4.0 (mainly in support of LINQ), that this addition may go unnoticed.

Variance in C# 4.0 - Anders Hejlsberg - Anders Hejlsberg

 

Terminology:

Invariant: A return parameter is invariant if we must use the exact match of the type name. In other words, neither covariance nor contravariance is permitted

Covariant: A parameter is covariant if we can use a more derived type as a substitute for the parameter type. In other words, a subclass instance can be used where a parent class instance was expected.

Contravariant: A return value is contravariant if we can assign the return type to a variable of a less derived type than the parameter. In other words, a super class instance can be used where a subclass instance was expected.

Variance in C# 4.0 - Anders Hejlsberg - Anders Hejlsberg

 

Generally, C# supports covariant parameters and contravariant return types. There has always been support for covariance and contravariance in C# - C# 4.0 will just ensure that generic delegates and interfaces will also behave they way we would expect.

Eric Lippert is the developer responsible for this feature of the C# 4.0 release and has an eleven-part blog series on just this topic. I would also recommend reading Charlie Calvert's article on this topic for some code samples.

Side Note: You do not need VS 2010 to experiment with these features - just download the framework to a test VM.

kick it on DotNetKicks.com

Tags: , ,

.NET 4.0 | C#



What are C# Generics - Part III

by agrace 24. April 2008 18:57

Panama Hat Personally, I think I am still in the process of making the final paradigm leap to generics. It will probably be some time yet before I am satisfied that I am applying the concept creatively enough in the early design phase. The end goal is to become comfortable enough with the new syntax to "genericize" my code and make it more type-safe and reusable overall.

Right now, a lot of people are overly-occupied with the latest 3.5 toys. If it ain't SilverLight or MVC it ain't worth talking about. It pays to concern oneself with the basic building blocks that make up the language of your choice. In my case, it is C# although I used C++ right through college and spent some time with Java. The point is that in an object-oriented world, such concepts as generics travel quite well across languages and underpin the development of a strong object view of things overall. The "drag and drop brigade" frequently have a problem grasping this.

Generic IL and Metadata

Nitty Gritty

Generics operate at the compiler level. It was necessary to change the metadata, compiler and IL instructions to make it all posssible. The upshot is that generics work across different .NET managed languages. This means that we can define a generic class in C# and consume it in VB. Score another one for code reuse :-)

Under the hood, the compiler generates the intermediate language (IL) which contains placeholders for the actual types which will be substituted at runtime. In other words, the generic types are "instantiated" at runtime. This is known as "lazy" specialization or "just-in-time". The accompanying metadata is used for compile-time type-checking and intellisense.

It is possible that code could try to use types which are not compatible with what was intended and "contraints" are provided as a measure of protection to prevent this happening. Remember, a generic class or method knows nothing about the arguments being passed to it. The compiler needs to know something more. Each type parameter can have a different set of constraints, expressed using a where clause. A parameter can have multiple constraints, separated by commas.

class Guitar < T1, T2, T3>
    where T1: Fender
    where T2: Gibson
    where T3: Martin
{
    ...
}


To recap, you will most likely find a use for generics with collections. It is well worth the time invested. Right now, I'm working my way through a copy of Professional .NET 2.0 Generics by Tod Golding. It's about the best book on the topic of Generics that I have come across. Happy coding!

kick it on DotNetKicks.com   PHP, ASP, .NET, JSP Resources, Reviews

Tags: ,

C#