Search Results

Search found 763 results on 31 pages for 'casting'.

Page 2/31 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Casting in mixed type calculations in C?

    - by yCalleecharan
    Hi, If I define these variables: double x0, xn, h; int n; and I have this mathematical expression: h = (xn - x0)/n; Is it necessary that I cast n into double prior doing the division for maximum accuracy like in h = (xn - x0)/ (double) n; I wrote a program to check the above but both expressions give the same answers. I understand that C will promote the integer to double type as variables xn and x0 are of type double but strangely enough in a book, the second expression with casting was emphasized. Thanks a lot...

    Read the article

  • casting a node to integer

    - by user1708762
    The code gives an error saying that "no operator matches these two operands" in the if comparison statement. I interpret,it should mean that "a node can't be converted/casted into an integer". But, the print statement prints an integer value for w[2] when used with %d format. Why is that happening? Isn't printf casting it? NODE *w=(NODE *)malloc(4*sizeof(NODE)); if(w[2]==0) printf("%d\n",w[2]); The structure of the node is- struct node{ int key; struct node *father; struct node *child[S]; int *ss; int current; };

    Read the article

  • Java Generic Casting Type Mismatch

    - by Kay
    public class MaxHeap<T extends Comparable<T>> implements Heap<T>{ private T[] heap; private int lastIndex; public void main(String[] args){ int i; T[] arr = {1,3,4,5,2}; //ERROR HERE ******* foo } public T[] Heapsort(T[]anArray, int n){ // build initial heap T[]sortedArray = anArray; for (int i = n-1; i< 0; i--){ //assert: the tree rooted at index is a semiheap heapRebuild(anArray, i, n); //assert: the tree rooted at index is a heap } //sort the heap array int last = n-1; //invariant: Array[0..last] is a heap, //Array[last+1..n-1] is sorted for (int j=1; j<n-1;j++) { sortedArray[0]=sortedArray[last]; last--; heapRebuild(anArray, 0, last); } return sortedArray; } protected void heapRebuild(T[ ] items, int root, int size){ foo } } The error is on the line with "T[arr] = {1,3,4,5,2}" Eclispe complains that there is a: "Type mismatch: cannot convert from int to T" I've tried to casting nearly everywhere but to no avail.A simple way out would be to not use generics but instead just ints but that's sadly not an option. I've got to find a way to resolve the array of ints "{1,3,4,5,2}" into an array of T so that the rest of my code will work smoothly.

    Read the article

  • casting Collection<SomeClass> to Collection<SomeSuperClass>

    - by skrebbel
    Hi all, I'm sure this has been answered before, but I really cannot find it. I have a java class SomeClass and an abstract class SomeSuperClass. SomeClass extends SomeSuperClass. Another abstract method has a method that returns a Collection<SomeSuperClass>. In an implementation class, I have a Collection<SomeClass> myCollection I understand that I cannot just return myCollection, because Collection<SomeClass> does not inherit from Collection<SomeSuperClass>. Nevertheless, I know that everything in myCollection is a SomeSuperClass because after all, they're SomeClass objects which extend SomeSuperClass. How can I make this work? I.e. I want public class A { private Collection<SomeClass> myCollection; public Collection<SomeSuperClass> getCollection() { return myCollection; //compile error! } } The only way I've found is casting via a non-generic type and getting unchecked warnings and whatnot. There must be a more elegant way, though? I feel that also using Collections.checkedSet() and friends are not needed, since it is statically certain that the returned collection only contains SomeClass objects (this would not be the case when downcasting instead of upcasting, but that's not what I'm doing). What am I missing? Thanks!

    Read the article

  • casting vs using the 'as' keyword in the CLR

    - by Frank V
    I'm learning about design patterns and because of that I've ended using a lot of interfaces. One of my "goals" is to program to an interface, not an implementation. What I've found is that I'm doing a lot of casting or object type conversion. What I'd like to know is if there is a difference between these two methods of conversion: public interface IMyInterface { void AMethod(); } public class MyClass : IMyInterface { public void AMethod() { //Do work } // other helper methods.... } public class Implementation { IMyInterface _MyObj; MyClass _myCls1; MyClass _myCls2; public Implementation() { _MyObj = new MyClass(); // What is the difference here: _myCls1 = (MyClass)_MyObj; _myCls2 = (_MyObj as MyClass); } } If there is a difference, is there a cost difference or how does this affect my program? Hopefully this makes sense. Sorry for the bad example; it is all I could think of... Update: What is "in general" the preferred method? (I had a question similar to this posted in the 'answers'. I moved it up here at the suggestion of Michael Haren. Also, I want to thank everyone who's provided insight and perspective on my question.

    Read the article

  • casting char[][] to char** causes segfault?

    - by Earlz
    Ok my C is a bit rusty but I figured I'd make my next(small) project in C so I could polish back up on it and less than 20 lines in I already have a seg fault. This is my complete code: #define ROWS 4 #define COLS 4 char main_map[ROWS][COLS+1]={ "a.bb", "a.c.", "adc.", ".dc."}; void print_map(char** map){ int i; for(i=0;i<ROWS;i++){ puts(map[i]); //segfault here } } int main(){ print_map(main_map); //if I comment out this line it will work. puts(main_map[3]); return 0; } I am completely confused as to how this is causing a segfault. What is happening when casting from [][] to **!? That is the only warning I get. rushhour.c:23:3: warning: passing argument 1 of ‘print_map’ from incompatible pointer type rushhour.c:13:7: note: expected ‘char **’ but argument is of type ‘char (*)[5]’ Are [][] and ** really not compatible pointer types? They seem like they are just syntax to me.

    Read the article

  • casting doubles to integers in order to gain speed

    - by antirez
    Hello all, in Redis (http://code.google.com/p/redis) there are scores associated to elements, in order to take this elements sorted. This scores are doubles, even if many users actually sort by integers (for instance unix times). When the database is saved we need to write this doubles ok disk. This is what is used currently: snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val); Additionally infinity and not-a-number conditions are checked in order to also represent this in the final database file. Unfortunately converting a double into the string representation is pretty slow. While we have a function in Redis that converts an integer into a string representation in a much faster way. So my idea was to check if a double could be casted into an integer without lost of data, and then using the function to turn the integer into a string if this is true. For this to provide a good speedup of course the test for integer "equivalence" must be fast. So I used a trick that is probably undefined behavior but that worked very well in practice. Something like that: double x = ... some value ... if (x == (double)((long long)x)) use_the_fast_integer_function((long long)x); else use_the_slow_snprintf(x); In my reasoning the double casting above converts the double into a long, and then back into an integer. If the range fits, and there is no decimal part, the number will survive the conversion and will be exactly the same as the initial number. As I wanted to make sure this will not break things in some system, I joined #c on freenode and I got a lot of insults ;) So I'm now trying here. Is there a standard way to do what I'm trying to do without going outside ANSI C? Otherwise, is the above code supposed to work in all the Posix systems that currently Redis targets? That is, archs where Linux / Mac OS X / *BSD / Solaris are running nowaday? What I can add in order to make the code saner is an explicit check for the range of the double before trying the cast at all. Thank you for any help.

    Read the article

  • Casting objects in C# (ASP.Net MVC)

    - by Mortanis
    I'm coming from a background in ColdFusion, and finally moving onto something modern, so please bear with me. I'm running into a problem casting objects. I have two database tables that I'm using as Models - Residential and Commercial. Both of them share the majority of their fields, though each has a few unique fields. I've created another class as a container that contains the sum of all property fields. Query the Residential and Commercial, stuff it into my container, cunningly called Property. This works fine. However, I'm having problems aliasing the fields from Residential/Commercial onto Property. It's quite easy to create a method for each property: fillPropertyByResidential(Residential source) and fillPropertyByCommercial(Commercial source), and alias the variables. That also works fine, but quite obviously will copy a bunch of code - all those fields that are shared between the two main Models. So, I'd like a generic fillPropertyBySource() that takes the object, and detects if it's Residential or Commercial, fills the particular fields of each respective type, then do all the fields in common. Except, I gather in C# that variables created inside an If are only in the scope of the if, so I'm not sure how to do this. public property fillPropertyBySource(object source) { property prop = new property(); if (source is Residential) { Residential o = (Residential)source; //Fill Residential only fields } else if (source is Commercial) { Commercial o = (Commercial)source; //Fill Commercial only fields } //Fill fields shared by both prop.price = (int)o.price; prop.bathrooms = (float)o.bathrooms; return prop; } "o" being a Commercial or Residential only exists within the scope of the if. How do I detect the original type of the source object and take action? Bear with me - the shift from ColdFusion into a modern language is pretty..... difficult. More so since I'm used to procedural code and MVC is a massive paradigm shift. Edit: I should include the error: The name 'o' does not exist in the current context For the aliases of price and bathrooms in the shared area.

    Read the article

  • Casting interfaces in java

    - by owca
    I had two separate interfaces, one 'MultiLingual' for choosing language of text to return, and second 'Justification' to justify returned text. Now I need to join them, but I'm stuck at 'java.lang.ClassCastException' error. Class Book is not important here. Data.length and FormattedInt.width correspond to the width of the line. The code : public interface MultiLingual { static int ENG = 0; static int PL = 1; String get(int lang); int setLength(int length); } class Book implements MultiLingual { private String title; private String publisher; private String author; private int jezyk; public Book(String t, String a, String p, int y){ this(t, a, p, y, 1); } public Book(String t, String a, String p, int y, int lang){ title = t; author = a; publisher = p; jezyk = lang; } public String get(int lang){ jezyk = lang; return this.toString(); } public int setLength(int i){ return 0; } @Override public String toString(){ String dane; if (jezyk == ENG){ dane = "Author: "+this.author+"\n"+ "Title: "+this.title+"\n"+ "Publisher: "+this.publisher+"\n"; } else { dane = "Autor: "+this.author+"\n"+ "Tytul: "+this.title+"\n"+ "Wydawca: "+this.publisher+"\n"; } return dane; } } class Data implements MultiLingual { private int day; private int month; private int year; private int jezyk; private int length; public Data(int d, int m, int y){ this(d, m, y, 1); } public Data(int d, int m, int y, int lang){ day = d; month = m; year = y; jezyk = lang; } public String get(int lang){ jezyk = lang; return this.toString(); } public int setLength(int i){ length = i; return length; } @Override public String toString(){ String dane=""; String miesiac=""; String dzien=""; switch(month){ case 1: miesiac="January"; case 2: miesiac="February"; case 3: miesiac="March"; case 4: miesiac="April"; case 5: miesiac="May"; case 6: miesiac="June"; case 7: miesiac="July"; case 8: miesiac="August"; case 9: miesiac="September"; case 10: miesiac="October"; case 11: miesiac="November"; case 12: miesiac="December"; } if(day==1){ dzien="st"; } if(day==2 || day==22){ dzien="nd"; } if(day==3 || day==23){ dzien="rd"; } else{ dzien="th"; } if(jezyk==ENG){ dane =this.day+dzien+" of "+miesiac+" "+this.year; } else{ dane = this.day+"."+this.month+"."+this.year; } return dane; } } interface Justification { static int RIGHT=1; static int LEFT=2; static int CENTER=3; String justify(int just); } class FormattedInt implements Justification { private int liczba; private int width; private int wyrownanie; public FormattedInt(int s, int i){ liczba = s; width = i; wyrownanie = 2; } public String justify(int just){ wyrownanie = just; String wynik=""; String tekst = Integer.toString(liczba); int len = tekst.length(); int space_left=width - len; int space_right = space_left; int space_center_left = (width - len)/2; int space_center_right = width - len - space_center_left -1; String puste=""; if(wyrownanie == LEFT){ for(int i=0; i<space_right; i++){ puste = puste + " "; } wynik = tekst+puste; } else if(wyrownanie == RIGHT){ for(int i=0; i<space_left; i++){ puste = puste + " "; } wynik = puste+tekst; } else if(wyrownanie == CENTER){ for(int i=0; i<space_center_left; i++){ puste = puste + " "; } wynik = puste + tekst; puste = " "; for(int i=0; i< space_center_right; i++){ puste = puste + " "; } wynik = wynik + puste; } return wynik; } } And the test code that shows this casting "(Justification)gatecrasher[1]" which gives me errors : MultiLingual gatecrasher[]={ new Data(3,12,1998), new Data(10,6,1924,MultiLingual.ENG), new Book("Sekret","Rhonda Byrne", "Nowa proza",2007), new Book("Tuesdays with Morrie", "Mitch Albom", "Time Warner Books",2003, MultiLingual.ENG), }; gatecrasher[0].setLength(25); gatecrasher[1].setLength(25); Justification[] t={ new FormattedInt(345,25), (Justification)gatecrasher[1], (Justification)gatecrasher[0], new FormattedInt(-7,25) }; System.out.println(" 10 20 30"); System.out.println("123456789 123456789 123456789"); for(int i=0;i < t.length;i++) System.out.println(t[i].justify(Justification.RIGHT)+"<----\n");

    Read the article

  • Bullet Physics - Casting a ray straight down from a rigid body (first person camera)

    - by Hydrocity
    I've implemented a first person camera using Bullet--it's a rigid body with a capsule shape. I've only been using Bullet for a few days and physics engines are new to me. I use btRigidBody::setLinearVelocity() to move it and it collides perfectly with the world. The only problem is the Y-value moves freely, which I temporarily solved by setting the Y-value of the translation vector to zero before the body is moved. This works for all cases except when falling from a height. When the body drops off a tall object, you can still glide around since the translate vector's Y-value is being set to zero, until you stop moving and fall to the ground (the velocity is only set when moving). So to solve this I would like to try casting a ray down from the body to determine the Y-value of the world, and checking the difference between that value and the Y-value of the camera body, and disable or slow down movement if the difference is large enough. I'm a bit stuck on simply casting a ray and determining the Y-value of the world where it struck. I've implemented this callback: struct AllRayResultCallback : public btCollisionWorld::RayResultCallback{ AllRayResultCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld) : m_rayFromWorld(rayFromWorld), m_rayToWorld(rayToWorld), m_closestHitFraction(1.0){} btVector3 m_rayFromWorld; btVector3 m_rayToWorld; btVector3 m_hitNormalWorld; btVector3 m_hitPointWorld; float m_closestHitFraction; virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace) { if(rayResult.m_hitFraction < m_closestHitFraction) m_closestHitFraction = rayResult.m_hitFraction; m_collisionObject = rayResult.m_collisionObject; if(normalInWorldSpace){ m_hitNormalWorld = rayResult.m_hitNormalLocal; } else{ m_hitNormalWorld = m_collisionObject->getWorldTransform().getBasis() * rayResult.m_hitNormalLocal; } m_hitPointWorld.setInterpolate3(m_rayFromWorld, m_rayToWorld, m_closestHitFraction); return 1.0f; } }; And in the movement function, I have this code: btVector3 from(pos.x, pos.y + 1000, pos.z); // pos is the camera's rigid body position btVector3 to(pos.x, 0, pos.z); // not sure if 0 is correct for Y AllRayResultCallback callback(from, to); Base::getSingletonPtr()->m_btWorld->rayTest(from, to, callback); So I have the callback.m_hitPointWorld vector, which seems to just show the position of the camera each frame. I've searched Google for examples of casting rays, as well as the Bullet documentation, and it's been hard to just find an example. An example is really all I need. Or perhaps there is some method in Bullet to keep the rigid body on the ground? I'm using Ogre3D as a rendering engine, and casting a ray down is quite straightforward with that, however I want to keep all the ray casting within Bullet for simplicity. Could anyone point me in the right direction? Thanks.

    Read the article

  • Casting good practice

    - by phenevo
    Hi, I've got 3 classes namespace ServerPart public class Car { } namespace ServerPart public class SUV:Car { public string Name {get;set;} public string Color {get;set;) } And namespace WebSericePart public class Car { } namespace WebSericePart:Car public class SUV { public string Name {get;set;} public string Color {get;set;) } And I've translator namespace WebServicepart.Translators public static class ModelToContract { public Car[] ToCars(ServerPart.Car[] modelCars) { List<Car> contractCars=new List<Car>(); foreach(ServerPart.Car modelCar in modelCars) { contractCars.Add(ToCar(modelCar); } return contractCars.ToArray(); } public Car ToCar(ServerPart.Car modelCar) { if(modelCar is ServerPart.SUV) { return ToSUV(modelCar); } else { throw new NotImplementedException("Not supported type of Car")' } } public Car ToSUV(ServerPart.Car modelCar) { SUV suv=new SUV; // suv.Name=((ServerPart.SUV)modelCar).Name suv.Color=((ServerPart.SUV)modelCar).Color // ?? Is good practice ?? Or //ServerPart.SUV suv=(ServerPart.SUV)modelCar //suv.Name=suv.Name //suv.Color=suv.Color // is better ?? return suv; } } Do I used some else bad practices ?? Or Everything is OK :) ?

    Read the article

  • Explicit casting doesn't work in default model binding

    - by Felix
    I am using ASP.NET MVC2 and Entity Framework. I am going to simplify the situation a little; hopefully it will make it clearer, not more confusing! I have a controller action to create address, and the country is a lookup table (in other words, there is a one-to-many relationship between Country and Address classes). Let's say for clarity that the field in the Address class is called Address.Land. And, for the purposes of the dropdown list, I am getting Country.CountryID and Country.Name. I am aware of Model vs. Input validation. So, if I call the dropdown field formLand - I can make it work. But if I call the field Land (that is, matching the variable in Address class) - I am getting the following error: "The parameter conversion from type 'System.String' to type 'App.Country' failed because no type converter can convert between these types." OK, this makes sense. A string (CountryID) comes from the form and the binder doesn't know how to convert it to Country type. So, I wrote the converter: namespace App { public partial class Country { public static explicit operator Country(string countryID) { AppEntities context = new AppEntities(); Country country = (Country) context.GetObjectByKey( new EntityKey("AppEntities.Countries", "CountryID", countryID)); return country; } } } FWIW, I tried both explicit and implicit. I tested it from the controller - Country c = (Country)"fr" - and it works fine. However, it never got invoked when the View is posted. I am getting the same "no type converter" error in the model. Any ideas how to hint to the model binder that there is a type converter? Thanks

    Read the article

  • QueryInterface fails at casting inside COM-interface implementation

    - by brecht
    I am creating a tool in c# to retrieve messages of a CAN-network (network in a car) using an Dll written in C/C++. This dll is usable as a COM-interface. My c#-formclass implements one of these COM-interfaces. And other variables are instantiated using these COM-interfaces (everything works perfect). The problem: The interface my C#-form implements has 3 abstract functions. One of these functions is called -by the dll- and i need to implement it myself. In this function i wish to retrieve a property of a form-wide variable that is of a COM-type. The COM library is CANSUPPORTLib The form-wide variable: private CANSUPPORTLib.ICanIOEx devices = new CANSUPPORTLib.CanIO(); This variable is also form-wide and is retrieved via the devices-variable: canreceiver = (CANSUPPORTLib.IDirectCAN2)devices.get_DirectDispatch(receiverLogicalChannel); The function that is called by the dll and implemented in c# public void Message(double dTimeStamp) { Console.WriteLine("!!! message ontvangen !!!" + Environment.NewLine); try { CANSUPPORTLib.can_msg_tag message = new CANSUPPORTLib.can_msg_tag(); message = (CANSUPPORTLib.can_msg_tag) System.Runtime.InteropServices.Marshal.PtrToStructure(canreceiver.RawMessage, message.GetType()); for (int i = 0; i < message.data.Length; i++) { Console.WriteLine("byte " + i + ": " + message.data[i]); } } catch (Exception e) { Console.WriteLine(e.Message); } } The error rises at this line: message = (CANSUPPORTLib.can_msg_tag)System.Runtime.InteropServices.Marshal.PtrToStructure(canreceiver.RawMessage, message.GetType()); Error: Unable to cast COM object of type 'System.__ComObject' to interface type 'CANSUPPORTLib.IDirectCAN2'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{33373EFC-DB42-48C4-A719-3730B7F228B5}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)). Notes: It is possible to have a timer-clock that checks every 100ms for the message i need. The message is then retrieved in the exact same way as i do now. This timer is started when the form starts. The checking is only done when Message(double) has put a variable to true (a message arrived). When the timer-clock is started in the Message function, i have the same error as above Starting another thread when the form starts, is also not possible. Is there someone with experience with COM-interop ? When this timer

    Read the article

  • Casting problems with Google Maps API

    - by Thiago
    Hi there, I'm trying to run the following line: Directions.loadFromWaypoints((Waypoint[])waypoints.toArray(), opts); But I'm getting: 23:41:44.595 [ERROR] [carathome] Uncaught exception escaped java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lcom.google.gwt.maps.client.geocode.Waypoint; at com.presasystems.gwt.carathome.client.widgets.MostrarLinhasPanel$1$1.onSuccess(MostrarLinhasPanel.java:72) at com.presasystems.gwt.carathome.client.widgets.MostrarLinhasPanel$1$1.onSuccess(MostrarLinhasPanel.java:1) at com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.onResponseReceived(RequestCallbackAdapter.java:216) at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:287) at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:393) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:157) at com.google.gwt.dev.shell.BrowserChannel.reactToMessagesWhileWaitingForReturn(BrowserChannel.java:1713) at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:165) at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:120) at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:507) at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:264) at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91) at com.google.gwt.core.client.impl.Impl.apply(Impl.java) at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:188) at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:157) at com.google.gwt.dev.shell.BrowserChannel.reactToMessages(BrowserChannel.java:1668) at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:401) at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:222) at java.lang.Thread.run(Unknown Source) Why? Shouldn't this cast work? How can I do this in an elegant fashion? Thanks in advance

    Read the article

  • Casting generics and the generic type

    - by Kragen
    Consider, I have the following 3 classes / interfaces: class MyClass<T> { } interface IMyInterface { } class Derived : IMyInterface { } And I want to be able to cast a MyClass<Derived> into a MyClass<IMyInterface> or visa-versa: MyClass<Derived> a = new MyClass<Derived>(); MyClass<IMyInterface> b = (MyClass<IMyInterface>)a; But I get compiler errors if I try: Cannot convert type 'MyClass<Derived>' to 'MyClass<IMyInterface>' I'm sure there is a very good reason why I cant do this, but I can't think of one. As for why I want to do this - The scenario I'm imagining is one whereby you ideally want to work with an instance of MyClass<Derived> in order to avoid lots of nasty casts, however you need to pass your instance to an interface that accepts MyClass<IMyInterface>. So my question is twofold: Why can I not cast between these two types? Is there any way of keeping the niceness of working with an instance of MyClass<Derived> while still being able to cast this into a MyClass<IMyInterface>?

    Read the article

  • casting void* to float* creates only zeros

    - by Paperflyer
    I am reading an audio file using CoreAudio (Extended Audio File Read Services). The audio data gets converted to 4-byte float and handed to me as a void* buffer. It can be played with Audio Queue Services, so its content is correct. Next, I want to draw a waveform and thus need access to the actual samples. So, I cast void* audioData to float*: Float32 *floatData = (Float32 *)audioData; When accessing this data however, I only get 0.0 regardless of the index. Float32 value = floatData[index]; // Is always zero for any index Am I doing something wrong with the cast?

    Read the article

  • c++ casting base class to derived class mess

    - by alan2here
    If I were to create a base class called base and derived classes called derived_1, derived_2 etc... I use a collection of instances of the base class, then when I retrieved an element and tried to use it I would find that C++ thinks it's type is that of the base class, probably because I retrieved it from a std::vector of base. Which is a problem when I want to use features that only exist for the specific derived class who's type I knew this object was when I put it into the vector. So I cast the element into the type it is supposed to be and found this wouldn't work. (derived_3)obj_to_be_fixed; And remembered that it's a pointer thing. After some tweaking this now worked. *((derived_3*)&obj_to_be_fixed); Is this right or is there for example an abc_cast() function that does it with less mess?

    Read the article

  • JAVA Casting error

    - by user1612725
    Im creating a program that uses Dijksrtras algorithm, im using nodes that represent cities on an imported map, and you can create edges between two cities on the map. My problem is every edge has a "weight" where it will represent distance in minutes and i have a function where i want to see the distance between the two edges. But i keep getting the error "Cannot cast from Stad to Edge" at the line Edge<Stad> selectedEdge = (Edge) fvf.visaFörbLista.getSelectedValue(); where "Stad" represents the city and "Edge" an edge. FormVisaförbindelse fvf = new FormVisaförbindelse(); for(;;){ try{ int svar = showConfirmDialog(null, fvf, "Ändra Förbindelser", JOptionPane.OK_CANCEL_OPTION); if (svar != YES_OPTION) return; if (fvf.visaFörbLista.isSelectionEmpty() == true){ showMessageDialog(mainMethod.this, "En Förbindelse måste valjas.","Fel!", ERROR_MESSAGE); return; } Edge<Stad> selectedEdge = (Edge) fvf.visaFörbLista.getSelectedValue(); FormÄndraförbindelse faf = new FormÄndraförbindelse(); faf.setförbNamn(selectedEdge.getNamn()); for(;;){ try{ int svar2 = showConfirmDialog(mainMethod.this, faf, "Ändra Förbindelse", OK_CANCEL_OPTION); if (svar2 != YES_OPTION) return; selectedEdge.setVikt(faf.getförbTid()); List<Edge<Stad>> edges = lg.getEdgesBetween(sB, sA); for (Edge<Stad> edge : edges){ if (edge.getNamn()==selectedEdge.getNamn()){ edge.setVikt(faf.getförbTid()); } } return; } catch(NumberFormatException e){ showMessageDialog(mainMethod.this, "Ogiltig inmatning.","Fel!", ERROR_MESSAGE); }

    Read the article

  • Casting a primitive int to a Number

    - by Tamer
    Let's say that I have the following: int a = 2; Number b = (Number) a; System.out.println(b); // Prints 2 http://java.sun.com/docs/books/jls/first_edition/html/15.doc.html#238146 says that a primitive value may not be cast to a reference type. Does Java know to create an Integer from the primitive int and then cast to the superclass? How exactly does Java handle this behind the scenes? Thanks!

    Read the article

  • Casting Generic Types

    - by David Rutten
    Public Function CastToT(Of T)(ByVal GenericType(Of Object) data) As GenericType(Of T) Return DirectCast(data, GenericType(Of T)) End Function The above clearly does not work. Is there any way to perform this cast if I know that all objects inside data are in fact of Type T?

    Read the article

  • Error in casting

    - by Nasser Hajloo
    I have a simpleAsp.net page which I make it Ajaxable. everything works fine but I face with a problem whenever a specific method calls. Actually the Browser tell me that Sys.WebForms.PageRequestManagerServerErrorException: Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.WebControl'. I do not know how to resolve it. Any help appriciates.

    Read the article

  • Type casting in TPC inheritance

    - by Mohsen Esmailpour
    I have several products like HotelProduct, FlightProduct ... which derived from BaseProduct class. The table of these products will be generated in TPC manner in database. There is OrderLine class which has a BaseProduct. My problem is when i select an OrderLine with related product i don't know how cast BaseProduct to derived product. for example i have this query: var order = (from odr in _context.Orders join orderLine in _context.OrderLines on odr.Id equals orderLine.OrderId join hotel in _context.Products.OfType<HotelProduct>() on orderLine.ProductId equals hotel.Id where odr.UserId == userId && odr.Id == orderId orderby odr.OrderDate descending select odr).SingleOrDefault(); In OrderLine i have BaseProduct properties not properties of HotelProduct. Is there any way to cast BaseProduct to derived class in OrderLine or any other solutions ?

    Read the article

  • Tentative date casting in tsql

    - by Tewr
    I am looking for something like TRYCAST in TSQL or an equivalent method / hack. In my case I am extracting some date data from an xml column. The following query throws "Arithmetic overflow error converting expression to data type datetime." if the piece of data found in the xml cannot be converted to datetime (in this specific case, the date is "0001-01-01" in some cases). Is there a way to detect this exception before it occurs? select [CustomerInfo].value('(//*:InceptionDate/text())[1]', 'datetime') FROM Customers An example of what I am trying to achieve in pseudocode with an imagined tsql function TRYCAST(expr, totype, defaultvalue): select TRYCAST( [CustomerInfo].value('(//*:InceptionDate/text())[1]', 'nvarchar(100)'), datetime, null) FROM Customers

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >