Difference between typecasting and parsing? - c#

What is the big difference between parsing and typecasting?
I try to use type casting to a string and it gives me error.
Something like this:
string str = "10";
int i = (int) str;

For type casting to work the types need to be compatible:
object str = 10;
int i = (int) str;
Parsing is conversion between different types:
string str = "10";
int i = int.Parse(str);

Casting works when the objects share some piece of inheritance. But in your case
int i = (int) str;
You are dealing with implicit automatic conversion. In which the compiler will automatically widden/losen a .NET built-in type. For a complete guide go here and look for Converting and Casting
Int32.Parse(...
Parsing is for when they are two unrelated objects, but there is a way of converting one way to another.

Related

Type does not contain definition of 'Round' and 'Parse'

I get this strange error and it doesn't compile. My code looks like this:
if (model.CreditType == "Extra")
{
decimal num1 = decimal.Parse(amountReturn.ToString()) / model.CreditPeriod;
((dynamic)base.ViewBag).MonthlyPayment = Math.Round(num1, 2,
MidpointRounding.AwayFromZero);
dynamic viewBag = base.ViewBag;
Type type = typeof(Math);
decimal num2 = num1;
Type type1 = typeof(decimal);
viewBag.MonthlyPaymentWithTax = type.Round(num2 +
type1.Parse(((dynamic)base.ViewBag).TaxToAdd.ToString()) /
model.CreditPeriod, 2, 1);
}
I will be very thankful if somebody explains me how to fix my problem. On compile it generates the following errors.
Thank you in advance!
I don't know asp.net but I think I could explain about your error.
When you use typeof(myobj) this expression returns an instance of System.Type, not a same of referencing type itself in code, like Int.Parse().
An instance of System.Type is representation of runtime type information. It's a kind of "meta" object, not same as referencing the type you want on code.
It you wish to call a specific method via System.Type object, you should find it first. This method of calling is called as "Reflection". I recommend you to not do this because it is not easy, needs boilerplate(?) and not needed in most time when you know your type. doc
I just recommend first cast your target type and just call the static method of type (like the other answer did). or use TryParse?
(code is not tested for compilation)
dynamic a = "123";
string a_casted = 123 as string;
if (a_casted == null) { return; }
int a_parsed = Int.Parse(a_casted);
As mentioned in the error, the Type doesn't contain a definition for both Round and Parse. You need to use Decimal.Parse and Decimal.Round instead
You need to use
viewBag.MonthlyPaymentWithTax = Decimal.Round(num2 +
Decimal.Parse(((dynamic)base.ViewBag).TaxToAdd.ToString()) /
model.CreditPeriod, 2);
You can read more on both methods here
Decimal.Round
Decimal.Parse

C# Cannot Implicity Convert type 'Char[]' to 'Char?'

I searched and searched, but couldn't find anything remotely similar.
According to everything I've come to know, it should work.
string strTest, strSubTest, strDesc;
using (GenericParser parser = new GenericParser())
{
parser.SetDataSource(#"D:\work.csv");
parser.ColumnDelimiter = #",".ToCharArray();
parser.FirstRowHasHeader = true;
parser.MaxBufferSize = 4096;
parser.MaxRows = 200;
while (parser.Read())
{
strTest = parser["Test"];
strSubTest = parser["Subtest"];
strDesc = parser["Description"];
Console.WriteLine(strTest);
The code that states #",".ToCharArray(); states the error in the title. I've never seen an implicit conversion like that before 'Char?'. Any idea what I did wrong?
If you need some background, I used the GenericParser found here: http://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F
(note the single quotes)
parser.ColumnDelimiter = ',';
the question mark is a modifier to value types like char, int, and double to make them nullable. So where char x = null; is a syntax error, char? x = null; works. char? actually a shorthand syntax for Nullable<char>. Nullable<T> can't be used with reference types, as they are already nullable. Nullable<T> objects have two properties, bool HasValue, which should be obvious, and T Value, which returns the encapsulated value if HasValue is true, or throws an exception if it is false.
So, you can't set Delimeter to a character array, because it is expecting either a character or null.

Difference between Casting, Parsing and Converting [duplicate]

This question already has answers here:
Is casting the same thing as converting?
(11 answers)
Closed 9 years ago.
I have been working on some code for a while. And I had a question: What's the difference among casting, parsing and converting? And when we can use them?
Casting is when you take a variable of one type and change it to a different type. You can only do that in some cases, like so:
string str = "Hello";
object o = str;
string str2 = (string)o; // <-- This is casting
Casting does not change the variable's value - the value remains of the same type (the string "Hello").
Converting is when you take a value from one type and convert it to a different type:
double d = 5.5;
int i = (int)d; // <---- d was converted to an integer
Note that in this case, the conversion was done in the form of casting.
Parsing is taking a string and converting it to a different type by understanding its content. For instance, converting the string "123" to the number 123, or the string "Saturday, September 22nd" to a DateTime.
Casting: Telling the compiler that an object is really something else without changing it (though some data loss may be incurred).
object obj_s= "12345";
string str_i = (string) obj; // "12345" as string, explicit
int small = 12345;
long big = 0;
big = small; // 12345 as long, implicit
Parsing: Telling the program to interpret (on runtime) a string.
string int_s = "12345";
int i = int.Parse(int_s); // 12345 as int
Converting: Telling the program to use built in methods to try to change type for what may be not simply interchangeable.
double dub = 123.45;
int i = System.Convert.ToInt32(dub); // 123 as int
These are three terms each with specific uses:
casting - changing one type to another. In order to do this, the
types must be compatible: int -> object; IList<T> -> IEnumerable<T>
parsing - typically refers to reading strings and extracting useful parts
converting - similar to casting, but typically a conversion would involve changing one type to an otherwise non-compatible type. An example of that would be converting objects to strings.
A cast from one type to another requires some form of compatibility, usually via inheritance or implementation of an interface. Casting can be implicit or explicit:
class Foo : IFoo {
// implementations
}
// implicit cast
public IFoo GetFoo() {
return Foo;
}
// explicit cast
public IFoo GetFoo() {
return Foo as IFoo;
}
There are quite a few ways to parse. We read about XML parsing; some types have Parse and TryParse methods; and then there are times we need to parse strings or other types to extract the 'stuff we care about'.
int.Parse("3") // returns an integer value of 3
int.TryParse("foo", out intVal) // return true if the string could be parsed; otherwise false
Converting may entail changing one type into another incompatible one. This could involve some parsing as well. Conversion examples would usually be, IMO, very much tied to specific contexts.
casting
(casting to work the types need to be compatible)
Converting between data types can be done explicitly using a cast
static void _Casting()
{
int i = 10;
float f = 0;
f = i; // An implicit conversion, no data will be lost.
f = 0.5F;
i = (int)f; // An explicit conversion. Information will be lost.
}
parsing (Parsing is conversion between different types:)
converts one type to another type can be called as parsing uisng int.parse
int num = int.Parse("500");
traversing through data items like XML can be also called as parsing
When user-defined conversions get involved, this usually entails returning a different object/value. user-defined conversions usually exist between value types rather than reference types, so this is rarely an issue.
converting
Using the Convert-class actually just helps you parse it
for more please refer http://msdn.microsoft.com/en-us/library/ms228360%28VS.80%29.aspx
This question is actually pretty complicated...
Normally, a cast just tells the runtime to change one type to another. These have to be types that are compatible. For example an int can always be represented as a long so it is OK to cast it to a long. Some casts have side-effects. For example, a float will drop its precision if it is cast to an int. So (int)1.5f will result in int value 1. Casts are usually the fastest way to change the type, because it is a single IL operator. For example, the code:
public void CastExample()
{
int i = 7;
long l = (long)i;
}
Performs the cast by running the IL code:
conv.i8 //convert to 8-byte integer (a.k.a. Int64, a.k.a. long).
A parse is some function that takes in once type and returns another. It is an actual code function, not just an IL operator. This usually takes longer to run, because it runs multiple lines of code.
For example, this code:
public void ParseExample()
{
string s = "7";
long l = long.Parse(s);
}
Runs the IL code:
call int64 [mscorlib]System.Int64::Parse(string)
In other words it calls an actual method. Internally, the Int64 type provides that method:
public static long Parse(String s) {
return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
And Number.Parse:
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Int64 ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
Int64 i = 0;
StringToNumber(value, options, ref number, numfmt, false);
if ((options & NumberStyles.AllowHexSpecifier) != 0) {
if (!HexNumberToInt64(ref number, ref i)) {
throw new OverflowException(Environment.GetResourceString("Overflow_Int64"));
}
}
else {
if (!NumberToInt64(ref number, ref i)) {
throw new OverflowException(Environment.GetResourceString("Overflow_Int64"));
}
}
return i;
}
And so on... so you can see it is actually doing a lot of code.
Now where things get more complicated is that although a cast is usually the fastest, classes can override the implicit and explicit cast operators. For example, if I write the class:
public class CastableClass
{
public int IntValue { get; set; }
public static explicit operator int(CastableClass castable)
{
return castable.IntValue;
}
}
I have overridden the explicit cast operator for int, so I can now do:
public void OverridedCastExample()
{
CastableClass cc = new CastableClass {IntValue = 7};
int i = (int)cc;
}
Which looks like a normal cast, but in actuality it calls my method that I defined on my class. The IL code is:
call int32 UnitTestProject1.CastableClass::op_Explicit(class UnitTestProject1.CastableClass)
So anyway, you typically want to cast whenever you can. Then parse if you can't.
Casting: or Parsing
A cast explicitly invokes the conversion operator from one type to another.
Casting variables is not simple. A complicated set of rules resolves casts. In some cases data is lost and the cast cannot be reversed. In others an exception is provoked in the execution engine.
int.Parse is a simplest method but it throws exceptions on invalid input.
TryParse
int.TryParse is one of the most useful methods for parsing integers in the C# language. This method works the same way as int.Parse.
int.TryParse has try and catch structure inside. So, it does not throw exceptions
Convert:
Converts a base data type to another base data type.
Convert.ToInt32, along with its siblings Convert.ToInt16 and Convert.ToInt64, is actually a static wrapper method for the int.Parse method.
Using TryParse instead of Convert or Cast is recommended by many programmers.
source:www.dotnetperls.com
Different people use it to mean different things. It need not be true outside .net world, but here is what I have understood in .net context reading Eric Lippert's blogs:
All transformations of types from one form to another can be called conversion. One way of categorizing may be
implicit -
a. representation changing (also called coercion)
int i = 0;
double d = i;
object o = i; // (specifically called boxing conversion)
IConvertible o = i; // (specifically called boxing conversion)
Requires implicit conversion operator, conversion always succeeds (implicit conversion operator should never throw), changes the referential identity of the object being converted.
b. representation preserving (also called implicit reference conversion)
string s = "";
object o = s;
IList<string> l = new List<string>();
Only valid for reference types, never changes the referential identity of the object being converted, conversion always succeeds, guaranteed at compile time, no runtime checks.
explicit (also called casting) -
a. representation changing
int i = 0;
enum e = (enum)i;
object o = i;
i = (int)o; // (specifically called unboxing conversion)
Requires explicit conversion operator, changes the referential identity of the object being converted, conversion may or may not succeed, does runtime check for compatibility.
b. representation preserving (also called explicit reference conversion)
object o = "";
string s = (string)o;
Only valid for reference types, never changes the referential identity of the object being converted, conversion may or may not succeed, does runtime check for compatibility.
While conversions are language level constructs, Parse is a vastly different thing in the sense it's framework level, or in other words they are custom methods written to get an output from an input, like int.Parse which takes in a string and returns an int.

casting to int in c#

I read that casting will throw an exception if the cast doesn't go through and that there's a better syntax to cast which return a null instead of an exception if the cast is not possible. But I forgot it. Any refresher?
thanks.
I think you are referring to the as cast. However as cannot be used on non-reference types so you cannot do int x = obj as int.
In order to parse an int or some other value-type you can use the type specific trycast methods..
int x;
bool success = int.TryParse(someString, out x);
I believe this is what you're looking for...
string s = "36";
int resultInt;
int.TryParse(s, out resultInt);
if it's originating from a string, you can always use a TryParse()
if(!Int.TryParse(s, out i))
(handle non-int code here)
In c# if you use int x = Convert.toInt32(string) it internally calls int.tryparse as the convert method is a static wrapper class for tryparse. I find it a bit cleaner to use, though it is in theory a bit slower.
You can use the "as" operator on reference types. But since an int can be null, you can't use that operator. So for a string object to string cast you could do this:
object o = "";
string s = o as string;
But couldn't do the same with an int.
What your looking for is the as
So int myCasted = myVar as int;
Which apparently won't work on non-nullable value types

C# enum to string auto-conversion?

Is it possible to have the compiler automatically convert my Enum values to strings so I can avoid explicitly calling the ToString method every time. Here's an example of what I'd like to do:
enum Rank { A, B, C }
Rank myRank = Rank.A;
string myString = Rank.A; // Error: Cannot implicitly convert type 'Rank' to 'string'
string myString2 = Rank.A.ToString(); // OK: but is extra work
No. An enum is its own type, so if you want to convert it to something else, you have to do some work.
However, depending on what you're doing with it, some methods will call ToString() on it automatically for you. For example, you can do:
Console.Writeline(Rank.A);
You are not probably looking for enums itself, but a list of string constant. It can fit your needs better in some scenarios.
Use this instead:
public static class Rank
{
public const string A = "A";
public const string B = "B";
public const string C = "C";
}
No, but at least you can do things with enums that will call their ToString() methods when you might need to use their string value, e.g.:
Console.WriteLine(Rank.A); //prints "A".
The correct syntax should be
myRank.ToString("F");
[Caution, hack] Unsure as to whether this is nasty, to me it seems a reasonable compromise.
var myEnumAsString = MyEnum+"";
Console.WriteLine(myEnumAsString); //MyEnum
This will force implicit ToString()

Categories

Resources