Click here to Skip to main content
15,892,927 members
Everything / Casting

Casting

casting

Great Reads

by Yisrael Lax
Library that provides custom casting functionality from one type to another between properties with disparate names and types
by Francesco Bagnasco
Just a quick sample to clarify what we can do and what we can't

Latest Articles

by Yisrael Lax
Library that provides custom casting functionality from one type to another between properties with disparate names and types
by Francesco Bagnasco
Just a quick sample to clarify what we can do and what we can't

All Articles

Sort by Score

Casting 

3 Apr 2018 by OriginalGriff
Any cast - implicit or explicit - changes the type of an object: but it doesn't actually change the object at all, it just checks that the object is of a type suitable to cast, and that such a cast operation exists. For example, explicit cast operators exist for int to decimal, double to float,...
24 Apr 2018 by Yisrael Lax
Library that provides custom casting functionality from one type to another between properties with disparate names and types
5 Apr 2014 by Homero Rivera
I hate to say it, but the cast on client side...Student s = (Student)bin.Deserialize(receive.BaseStream);will never work, not like that at least.Why? For security reasons... How about someone forging a "Server.Student" and send that to your Client with malicious data?If your...
13 Nov 2015 by CPallini
I would replaceQuote:string str = "";char chr = i;stringstream chartostr; chartostr > str;withstring str;str += static_cast(i);I don't understand the purpose of the for loop. What are you trying to do?
31 Mar 2018 by Mehdi Gholam
Most likely a shortcoming of the compiler processor, i.e. the compiler takes one side of the ':' as the output type (probably the left) and assumes the second (right) must match otherwise throws and error without checking the inheritance tree in the case of Dog and Cat and the left side of the...
29 Jan 2019 by CHill60
Your ExecuteScalar command is returning Null (see the comment from @Richard-Deeming) You should check for the null before attempting to cast the return value. A neat way of doing that is as follows: object result = cmdSELECT.ExecuteScalar(); result = (result == DBNull.Value) ? null : result;...
18 May 2022 by CPallini
Don't use C-like casts in C++ code. C++ features dynamic_cast. Try #include using namespace std; class Base { public: virtual void funcBase() = 0; virtual ~Base(){} }; class DeriveOne : public Base { public: const char*...
15 Feb 2017 by Richard Deeming
Quote:Convert.ChangeType(newVa...
1 Apr 2018 by BillWoodruff
When you specify the return Type, and the ternary values that may be returned are of different Types, the compiler must check if a Type conversion is possible. These work because the compiler can determine there is a conversion possible: bool boolVal = true; Animal a1 = boolVal ? new Dog() :...
1 Apr 2018 by OriginalGriff
Assuming that you have code like this somewhere: public class Animal { ... } public class Dog : Animal { ... } Then you know that a Dog is an Animal - so you can assign a Dog instance to any variable which can contain a Dog or an Animal: Dog dog = new Dog(); Animal animal =...
8 Apr 2018 by Maciej Los
Quote: It doesn't work because they differ in their generic parameters. I don't understand above statement. Nevertheless... In a short: You cannot create a list of base class by passing new list of derived class! You have to explicit convert derived class into base class: List...
14 Aug 2018 by Richard MacCutchan
static_cast
18 Jul 2022 by CPallini
If the classes DeriveOne, DeriveTwo derive polymorphically from Base then you may use dynamic_cast, e.g.std::cout (base[0]))->getStr()
7 Mar 2023 by OriginalGriff
Don't use NVARCHAR - use VARBINRY (if they are small, less than 64Kbytes) or BLOB (if they are large) instead - or better, store them on a shared folder as files, and store the path in the DB. NVARCHAR data isn't binary - it's Unicode text, and...
8 May 2014 by saleem_deek
Can anyone give me a method to convert the result of a select query to list of class?*I want that so I can later use LINK to objects* I'm using sql server 2008 and vb.net. For example, I have a table in DB having two columns:{ProductID, ProductName}I execute a select query "Select *...
8 May 2014 by Maciej Los
SamplePublic Class Product Private pid As Integer = 0 Private pname AS String = String.Empty Public Property ProductID As Integer Get Return pid End Get Set (value As Integer) pid = value End Set End...
24 Jun 2014 by bginsburg
I'm trying to cast DataTableReader to NpgSqlDataReader (its an abstract class) with no success. tried inheriting from it but than i cant because it has internal function that could not be override. The final thing im trying to do is move an object of NpgSqlDataReader from one process to...
22 May 2015 by sha3feb
I have a COM Class which is registered in to ROT, through an other application i am fetching the instance of my com class from ROT and casting it to its type giving following error.Unable to cast COM object of type 'System.__ComObject' to interface type 'ROTViewer.IHandleVIParentInfo'. This...
20 Jun 2015 by OriginalGriff
Casting is changing the logical type of a value from one type to another, and (normally) doesn't alter information (exceptions exist for casting between number types: double to int for example will throw away data to the left of the decimal point, int to byte would throw away all large values...
13 Nov 2015 by Member 12137990
for(int i=0; i> str;} i want to convert char to string, above code is work corretly, but is there a pro way to do this ?
13 Nov 2015 by Matt T Heffron
With str declared inside the body of your for loop, when the loop exits you have nothing to show for it! Wouldn't something like this get you what you want?string Ascii7(128, '\0');for (int i = 1; i (i);}
15 Mar 2016 by Trader999
Sorry a very simple question for more experienced programmers.How to I cast a linq to sql query to a decimal and return it from a function?The (decimal) cast below doesn't work.Thanks for the help!What I have tried:static decimal GET_MC_DATA_EAV(int ID, string B_C, string...
16 May 2016 by Bhavika Mdm
In my Table valued function, I have a variable of type date. I need to compare it (in a where clause) with the values of a column in a table, whose type is datetime2. Can anyone please help me with this, as the cast is not working for me.What I have tried:Following is my code:select...
16 May 2016 by Maciej Los
OK, OP already has found solution:Quote:I got the solution. The issue was that, the date part was getting converted to datetime2, but with time as 00:00:00. Then I did in the following way, and it worked.select *from Table1where [Date1] >= DATEADD(MS,-1,CAST(DATEADD(DD,1,@toDate) AS...
20 Jan 2017 by Member 12959504
Why do I need casting in some instances in java but not in other ones? For e.g I do not need to cast the expression byte i = 4 * 5 but I need to cast the expression byte r = i * 5. Why is this the case?What I have tried:I wrote a java program where I tried it
19 Jan 2017 by OriginalGriff
Because the compiler "knows" the value of 4 * 5 will fit in a byte, so it can treat it as a byte value. When you try to multiply an integer by a constant the result will be an integer - and a conversion to byte will potentially lose information (since a byte can only hold 8 bits, and an integer...
20 Jan 2017 by CPallini
Because in the right side ofbyte i = 4 * 5;there is a constat expression, evaluated at 'compile time' and so is is know in advance it fits in a byte.On the other hand, on the right side ofbyte r = i * 5.there is a variable, so it cannot be avaluated at 'compile time', automatic type...
14 Feb 2017 by Ralf Meier
The Object in which you want to cast must be declared as the type which should be the Destination ...Some parts could not be variable ... they (the type from this) must be specified ...
1 Apr 2018 by The_Unknown_Member
How does this code work without an explicit cast? static void Main() { IList dogs = new List(); IEnumerable animals = dogs; } I am talking about this line: "IEnumerable animals = dogs;" You can see here that I...
1 Apr 2018 by Christiaan van Bergen
Hi, This works because probably the Dog class is derived from the Animal class. Making the Dog an Animal. public class Animal{} public class Dog : Animal {} This means that in a collection of Animal, we can always put a Dog. All dogs are animals, but not all animals are dogs. Now, if we were...
1 Apr 2018 by PIEBALDconsult
Read up on Covariance and Contravariance (C#) | Microsoft Docs[^]
3 Apr 2018 by The_Unknown_Member
I've always thought that the explicit cast is just a way to tell the compiler that I know what I'm doing when it doesn't seem so For example: static void Main() { object blabla = new Derived(); AcceptABase(blabla); /* This call to the method won't work because...
8 Apr 2018 by The_Unknown_Member
Hi. I was experimenting with the concept of Covariance in Generic interfaces and I came across something that I want to ask you about I know that this code won't work: List randomList = new List(); It doesn't work because they differ in their generic parameters. This code also...
14 Aug 2018 by Ahmed AE
I have a problem with understanding the following line of code: static_cast(&QButtonGroup::m_buttonGroup) What I have tried: I searched for the static_cast, and understand it, i know that in this code we are trying to convert the object ...
7 Nov 2018 by TheBigBearNow
Hello all, I’m not sure why I’m getting a cast error. I can login as an Admin with no problem. I am using inheritance with customer class inheriting properties from user. A admin is just a normal user. Customer only has a few extra properties but before a lil earlier I was able to run my program...
7 Nov 2018 by OriginalGriff
WE can't see the definitions of loginUser and user which are the only explicit casts in that code; we also can't see what type SQLuserAccess.UserLogin returns, or what is in user before you cast that. So run your code in the debugger, and look at exactly what the variables contain. At a guess,...
29 Jan 2019 by TheBigBearNow
Hello all, I am creating a new Customer and in my C# SQL query I am getting the error “Invalid cast operation error.” I have a User and I am grabbing info from that user and inserting it into Customer. I was getting a foreign key error but I removed the foreign key so I could insert data now im...
9 Nov 2018 by TheBigBearNow
current error: Object reference not set to an instance of an object I was getting invalid cast exception error but i changed (int) to Convert.toInt32 and that went away. I go to debug it and the on my button click and the code runs all the way through not stopping at any of my breakpoints. The...
9 Nov 2018 by OriginalGriff
The debugger is pretty much the only way you will find this: if you aren't hitting the breakpoints, then either they aren't in the right place, or you are not debugging the code you are executing. So: try it again. Go to the "Debug" menu and select the "Exceptions..." menu item. In the...
9 Sep 2021 by Nils Leonhardt
Hello, I'm trying to create a short 2D game where you can wait x amount of time to get for example 50 "troops". This for now works fine, but now I need a script that detects the number of troops I have (at the startpoint) and send them out, just...
22 May 2022 by Phoenix Liveon
We have this kind of set-up; a custom classes class Base { // public: // virtual void funcBase(); }; class DeriveOne : public Base { public: char* funcDeriveOne(); // void funcBase() final override; }; Class...
20 Jul 2022 by Phoenix Liveon
How do we properly downcast an array of Base objects to their corresponding Derive type/object? pseudocode: Base b[] = { Derive1("dOne"), Derive2(2) } print ((Derive1)b[0]).getSpecialMemFuncOfDerive1() print...
11 Sep 2014 by Francesco Bagnasco
Just a quick sample to clarify what we can do and what we can't
3 Apr 2018 by Dave Kreskowiak
It's not changing the type of the instance. Casting just means "I'm going to treat this instance as this type", but this only works if the type you're casting it to is somewhere in the inheritance tree of the instance. Well, somewhere above the instances' original type. So, say you have the...
5 Apr 2014 by Member 10727293
I am developing a client server application in C#.I am sending from my server to client an object of `Student` type which I serialize on the server side and deserialize on client side. The serialization and deserialization are as follows : // server side serialization. Student s1...
1 Apr 2018 by The_Unknown_Member
Why do I need explicit cast in this case: class Program { static void Main() { bool boolVal = true; Animal a = boolVal ? new Dog() : new Cat(); } } class Animal { } class Dog : Animal { } class Cat : Animal { } At this...
15 Mar 2016 by OriginalGriff
Answered only to remove from unanswered list: solved by OP (with a little help!)
20 Jun 2015 by GeorgeZiozas
I am reading a BOOK about c# and i have come across some kinda weird concepts,at the time i am confused about Casting and Parsing. I know that Casting and Parsing are helping me to achieve the same thing but. 1) When i use eachone?2) Whats their differences?Simple examples would be...
23 Mar 2014 by Member 10692314
Hi there,I have a problem where I am using entity framework to update and create a Music table. I have a testing project where i built the entity using a builder class called MusicBulider. The builder class inherits the Music model. When I try and create the class and update via EF, I...
8 Mar 2023 by shamas saeed
-- Image Export Stored Procedure Alter PROCEDURE dbo.usp_ExportImage ( @id int ) AS BEGIN DECLARE @ImageData varbinary(max); DECLARE @Path2OutFile NVARCHAR (2000); DECLARE @Obj INT; Declare @File varchar(100); SET NOCOUNT ON ...
15 Feb 2017 by BoySetsFire
Richard, THANK YOU!!!Yesterday, after 10 hours working was my brain, like a limp biscuit ;)new day, new luck :)Many Thanks to everyone who has read this threadbr,Benny
15 Feb 2017 by BoySetsFire
Hi Experts!I have a little problem.I want to manipulate a reflected object, but i am too stupid to cast the datatype :(Please help me :)This is my idea:But it doesn't workmyObjectFromDB = GetFromDB(); // Get the object via Entity Framework form...
29 Jan 2019 by Ravi Gaur 11
connection.Open(); cmdCreate.ExecuteNonQuery(); string SQLselect = "SELECT @@IDENTITY FROM Customers"; SqlCommand cmdSELECT = new SqlCommand(SQLselect, connection); int CustomerId = (int)cmdSELECT.ExecuteScalar(); return CustomerId; error is in this section, ...
8 Mar 2023 by shamas saeed
I got a solution luckily, CAST('' AS XML).value('xs:base64Binary(sql:column("picturedata"))' , 'VARBINARY(MAX)')