Search Results

Search found 1868 results on 75 pages for 'cast'.

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

  • From varchar(36) to UNIQUEIDENTIFIER

    - by jgonchik
    I am trying to cast an AuctionId that is a UNIQUEIDENTIFIER to an varchar(36) and then back to an UNIQUEIDENTIFIER. Please help me. CAST((SUBSTRING(CAST([AuctionId] as VARCHAR(36)), 0, 35) + '1') AS UNIQUEIDENTIFIER) But I keep getting this error: Msg 8169, Level 16, State 2, Line 647 Conversion failed when converting from a character string to uniqueidentifier. Thanks in advance

    Read the article

  • Cast ASP type object to HtmlControl

    - by Joris
    Hey'all How do I cast a li dom element as HtmlControl from an ASP type object? I tried it like this: var li = (HtmlControl)sender; I get a InvalidCastException... The thing is, I want to make the li (a tab) clickable, and then update an UpdatePanel... But when I start like this <li id="li" runat="server" onclick="tab2_Click"> FooBar </li> I get an error because the object is not defined... how to cast?

    Read the article

  • SQL Server - CAST AND DIVIDE

    - by rs
    DECLARE @table table(XYZ VARCHAR(8) , id int) INSERT INTO @table SELECT '4000', 1 UNION ALL SELECT '3.123', 2 UNION ALL SELECT '7.0', 3 UNION ALL SELECT '80000', 4 UNION ALL SELECT NULL, 5 SELECT CASE WHEN PATINDEX('^[0-9]{1,5}[\.][0-9]{1,3}$', XYZ) = 0 THEN XYZ WHEN PATINDEX('^[0-9]{1,8}$',XYZ) = 0 THEN CAST(XYZ AS decimal(18,3))/1000 ELSE NULL END FROM @table This part - CAST(XYZ AS decimal(18,3))/1000 doesn't divide value it gives me more number of zeros after decimal instead of dividing it. (I even enclosed that in brackets and tried but same result) Am i doing something wrong here?

    Read the article

  • Casting between classes that share the same interface

    - by Chad
    I have two interfaces IHeaderRow, and IDetailRow I then have an object that implements both RawRow:IHeaderRow, IDetailRow I then need to cast it to HeaderRow which implements IHeaderRow. But when I try, it ends up being null or giving an exception. I can cast ObjectRawRow to either interface IHeaderRow, or IDetailRow var ObjectIHeaderRow = ObjectRawRow as IHeaderRow; var ObjectIDetailRow = ObjectRawRow as IDetailRow; But I can not cast ObjectRawRow to HeaderRow , or ObjectIHeaderRow to HeaderRow. It throws the error Cannot convert source type 'IA' to target type 'A' I need to cast it into the actual class HeaderRow. Thoughts?

    Read the article

  • How cast in XML for aggregate functions

    - by renegm
    In SQL Server 2008. I need execute a query like that: DECLARE @x AS xml SET @x=N'<r><c>First Text</c></r><r><c>Other Text</c></r>' SELECT @x.query('fn:max(r/c)') But return nothing (apparently because convert xdt:untypedAtomic to numeric) How to "cast" r/c to varchar? Something like SELECT @x.query('fn:max(«CAST(r/c «AS varchar(20))»)') Edit: Using Nodes the function MAX is from T-SQL no fn:max function In this code: DECLARE @x xml; SET @x = ''; SELECT @x.query('fn:max((1, 2))'); SELECT @x.query('fn:max(("First Text", "Other Text"))'); both query return expected: 2 and "Other Text" fn:max can evaluate string expression ad hoc. But the first query dont work. How to force string arguments to fn:max?

    Read the article

  • Doctrine SQL Server uniqueidentifier isn't cast as char or nvarchar when retrieved from the database

    - by Tres
    When I retrieve a record from the database which has a column of type "uniqueidentifier", Doctrine fills it with "null" rather than the unique id from the database. Some research and testing has brought this down to a PDO/dblib driver issue. When directly querying via PDO, null is returned in place of the unique id. For reference, http://trac.doctrine-project.org/ticket/1096, has a bit on this, however, it was updated 11 months ago with no comment for resolution. A way around this, as mentioned at http://bugs.php.net/bug.php?id=24752&edit=1, is to cast the column as a char. However, it doesn't seem Doctrine exposes the native field type outside of generating models which makes it a bit hard to detect uniqueidentifier types and cast them internally when building the sql query. Has anyone found a workaround for this?

    Read the article

  • Cast IEnumerable<Inherited> To IEnumerable<Base>

    - by david2342
    I'm trying to cast an IEnumerable of an inherited type to IEnumerable of base class. Have tried following: var test = resultFromDb.Cast<BookedResource>(); return test.ToList(); But getting error: You cannot convert these types. Linq to Entities only supports conversion primitive EDM-types. The classes involved look like this: public partial class HistoryBookedResource : BookedResource { } public partial class HistoryBookedResource { public int ResourceId { get; set; } public string DateFrom { get; set; } public string TimeFrom { get; set; } public string TimeTo { get; set; } } public partial class BookedResource { public int ResourceId { get; set; } public string DateFrom { get; set; } public string TimeFrom { get; set; } public string TimeTo { get; set; } } [MetadataType(typeof(BookedResourceMetaData))] public partial class BookedResource { } public class BookedResourceMetaData { [Required(ErrorMessage = "Resource id is Required")] [Range(0, int.MaxValue, ErrorMessage = "Resource id is must be an number")] public object ResourceId { get; set; } [Required(ErrorMessage = "Date is Required")] public object DateFrom { get; set; } [Required(ErrorMessage = "Time From is Required")] public object TimeFrom { get; set; } [Required(ErrorMessage = "Time to is Required")] public object TimeTo { get; set; } } The problem I'm trying to solve is to get records from table HistoryBookedResource and have the result in an IEnumerable<BookedResource> using Entity Framework and LINQ. UPDATE: When using the following the cast seams to work but when trying to loop with a foreach the data is lost. resultFromDb.ToList() as IEnumerable<BookedResource>; UPDATE 2: Im using entity frameworks generated model, model (edmx) is created from database, edmx include classes that reprecent the database tables. In database i have a history table for old BookedResource and it can happen that the user want to look at these and to get the old data from the database entity framework uses classes with the same name as the tables to receive data from db. So i receive the data from table HistoryBookedResource in HistoryBookedResource class. Because entity framework generate the partial classes with the properties i dont know if i can make them virtual and override. Any suggestions will be greatly appreciated.

    Read the article

  • How to cast correctly a struct in C++

    - by kriau
    Consider a code excerpt below: typedef struct tagTHREADNAME_INFO { DWORD dwType; LPCTSTR szName; DWORD dwThreadID; DWORD dwFlags; } THREADNAME_INFO; const THREADNAME_INFO info = { 0x1000, threadName, CurrentId(), 0}; ::RaiseException(kVCThreadNameException, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); How to cast correctly into ULONG_PTR* using C++ style cast? p.s. it's platform dependent code.

    Read the article

  • New cast exception with VS2010/.Net 4

    - by Trevor
    [ Updated 25 May 2010 ] I've recently upgraded from VS2008 to VS2010, and at the same time upgraded to .Net 4. I've recompiled an existing solution of mine and I'm encountering a Cast exception I did not have before. The structure of the code is simple (although the actual implementation somewhat more complicated). Basically I have: public class SomeClass : ISomeClass { // Stuff } public static class ClassFactory { public static IInterface GetClassInstance<IInterface>(Type classType) { return (IInterface)Activator.CreateInstance(classType); // This throws a cast exception } } // Call the factory with: ISomeClass anInstance = ClassFactory.GetClassInstance<ISomeClass>(typeof(SomeClass)); Ignore the 'sensibleness' of the above - its provides just a representation of the issue rather than the specifics of what I'm doing (e.g. constructor parameters have been removed). The marked line throws the exception: Unable to cast object of type 'Namespace.SomeClass' to type 'Namespace.ISomeClass'. I suspect it may have something to do with the additional DotNet security (and in particular, explicit loading of assemblies, as this is something my app does). The reason I suspect this is that I have had to add to the config file the setting: <runtime> <loadFromRemoteSources enabled="true" /> </runtime> .. but I'm unsure if this is related. Update I see (from comments) that my basic code does not reproduce the issue by itself. Not surprising I suppose. It's going to be tricky to identify which part of a largish 3-tier CQS system is relevant to this problem. One issue might be that there are multiple assemblies involved. My static class is actually a factory provider, and the 'SomeClass' is a class factory (relevant in that the factories are 'registered' within the app via explicit assembly/type loading - see below) . Upfront I use reflection to 'register' all factories (i.e. classes that implement a particular interface) and that I do this when the app starts by identifying the relevant assemblies, loading them and adding them to a cache using (in essence): Loop over (file in files) { Assembly assembly = Assembly.LoadFile(file); baseAssemblyList.Add(assembly); } Then I cache the available types in these assemblies with: foreach (Assembly assembly in _loadedAssemblyList) { Type[] assemblyTypes = assembly.GetTypes(); _loadedTypesCache.AddRange(assemblyTypes); } And then I use this cache to do a variety of reflection operations, including 'registering' of factories, which involves looping through all loaded (cached) types and finding those that implement the (base) Factory interface. I've experienced what may be a similar problem in the past (.Net 3.5, so not exactly the same) with an architecture that involved dynamically creating classes on the server and streaming the compiled binary of those classes to the client app. The problem came when trying to deserialize an instance of the dynamic class on the client from a remote call: the exception said the class type was not know, even though the source and destination types were exactly the same name (including namespace). Basically the cross boundry versions of the class were not recognised as being the same. I solved that by intercepting the deserialization process and explicitly defining the deseriazation class type in the context of the local assemblies. This experience is what makes me think the types are considered mismatched because (somehow) the interface of the actual SomeClass object, and the interface of passed into the Generic method are not considered the same type. So (possibly) my question for those more knowledgable about C#/DotNet is: How does the class loading work that somehow my app thinks there are two versions/types of the interface type and how can I fit that? [ whew ... anyone who got here is quite patient .. thanks ]

    Read the article

  • Reflection: cast an object to subclass without use instaceof

    - by Fabrizio
    I have this simple interface/class: public abstract class Message { } public class Message1 extends Message{ } public class Message2 extends Message{ } And an utility class: public class Utility { public void handler(Message m){ System.out.println("Interface: Message"); } public void handler(Message1 m){ System.out.println("Class: Message1"); } public void handler(Message2 m){ System.out.println("Class: Message2"); } } Now, the main class: public static void main(String[] args) { Utility p=new Utility(); Message1 m1=new Message1(); p.handler(m1); Message m=(Message) m1; p.handler(m); } The output is Class: Message1 Interface: Message I would that p.handler(m) call the method p.handler(m:Message1) I don't want use the "manual" command instanceof because I have many cases: if(m instance of Message1) p.handler((Message1)m) else if (m instanceof Message2) p.handler((Message2)m) ... If I call m.getClass() I obtain "mypackage.Message1", so the subclass and not the superclass. I try with this code (use reflection): p.handler(m.getClass().cast(m)); But the output is Interface: Message So, this is my problem. I would do a runtime cast of superclass object to subclassobject without use the "code command" istanceof. I would a right command like this: p.handler((m.getclass)m); How can I obtain it? It's possible? Thank in advance. Fabrizio

    Read the article

  • Which cast am I using?

    - by Knowing me knowing you
    I'm trying to cast away const from an object but it doesn't work. But if I use old C-way of casting code compiles. So which casting I'm suppose to use to achieve this same effect? I wouldn't like to cast the old way. //file IntSet.h #include "stdafx.h" #pragma once /*Class representing set of integers*/ template<class T> class IntSet { private: T** myData_; std::size_t mySize_; std::size_t myIndex_; public: #pragma region ctor/dtor explicit IntSet(); virtual ~IntSet(); #pragma endregion #pragma region publicInterface IntSet makeUnion(const IntSet&)const; IntSet makeIntersection(const IntSet&)const; IntSet makeSymmetricDifference(const IntSet&)const; void insert(const T&); #pragma endregion }; //file IntSet_impl.h #include "StdAfx.h" #include "IntSet.h" #pragma region ctor/dtor template<class T> IntSet<T>::IntSet():myData_(nullptr), mySize_(0), myIndex_(0) { } IntSet<T>::~IntSet() { } #pragma endregion #pragma region publicInterface template<class T> void IntSet<T>::insert(const T& obj) { /*Check if we are initialized*/ if (mySize_ == 0) { mySize_ = 1; myData_ = new T*[mySize_]; } /*Check if we have place to insert obj in.*/ if (myIndex_ < mySize_) {//IS IT SAFE TO INCREMENT myIndex while assigning? myData_[myIndex_++] = &T(obj);//IF I DO IT THE OLD WAY IT WORKS return; } /*We didn't have enough place...*/ T** tmp = new T*[mySize_];//for copying old to temporary basket std::copy(&myData_[0],&myData_[mySize_],&tmp[0]); } #pragma endregion Thanks.

    Read the article

  • Cast Object to Generic List

    - by CrazyJoe
    I have 3 generict type list. List<Contact> = new List<Contact>(); List<Address> = new List<Address>(); List<Document> = new List<Document>(); And save it on a variable with type object. Now i nedd do Cast Back to List to perfom a foreach, some like this: List<Contact> = (List<Contact>)obj; But obj content change every time, and i have some like this: List<???> = (List<???>)obj; I have another variable holding current obj Type: Type t = typeof(obj); Can i do some thing like that??: List<t> = (List<t>)obj; Obs: I no the current type in the list but i need to cast , and i dont now another form instead: List<Contact> = new List<Contact>(); Help Plz!!!

    Read the article

  • Generic <T> how cast ?

    - by Kris-I
    Hi, I have a "Product" base class, some other classes "ProductBookDetail","ProductDVDDetail" inherit from this class. I use a ProductService class to make operation on these classes. But, I have to do some check depending of the type (ISBN for Book, languages for DVD). I'd like to know the best way to cast "productDetail" value, I receive in SaveOrupdate. I tried GetType() and cast with (ProductBookDetail)productDetail but that's not work. Thanks, var productDetail = new ProductDetailBook() { .... }; var service = IoC.Resolve<IProductServiceGeneric<ProductDetailBook>>(); service.SaveOrUpdate(productDetail); var productDetail = new ProductDetailDVD() { .... }; var service = IoC.Resolve<IProductServiceGeneric<ProductDetailDVD>>(); service.SaveOrUpdate(productDetail); public class ProductServiceGeneric<T> : IProductServiceGeneric<T> { private readonly ISession _session; private readonly IProductRepoGeneric<T> _repo; public ProductServiceGeneric() { _session = UnitOfWork.CurrentSession; _repo = IoC.Resolve<IProductRepoGeneric<T>>(); } public void SaveOrUpdate(T productDetail) { using (ITransaction tx = _session.BeginTransaction()) { //here i'd like ot know the type and access properties depending of the class _repo.SaveOrUpdate(productDetail); tx.Commit(); } } }

    Read the article

  • Cast base class object to derived class

    - by Popgalop
    Lets say I have two classes, animal and dog like this. class Animal { }; class Dog : public Animal { }; And I have an animal object named animal, that is actually an instance of dog, how would I cast it back to dog? This may seem like an odd question, but I need it because I am writing a programming language interpreter, and on the stack everything is stored as a BaseObject, and all the other datatypes extend BaseObject. How would I cast the base object from the stack, to a specific data type? I have tried something like this Dog dog = static_cast<Dog>(animal); But it gives me an error 1>------ Build started: Project: StackTests, Configuration: Debug Win32 ------ 1> StackTests.cpp 1>c:\users\owner\documents\visual studio 2012\projects\stacktests\stacktests\stacktests.cpp(173): error C2440: 'static_cast' : cannot convert from 'Animal' to 'Dog' 1> No constructor could take the source type, or constructor overload resolution was ambiguous 1>c:\users\owner\documents\visual studio 2012\projects\stacktests\stacktests\stacktests.cpp(173): error C2512: 'Dog' : no appropriate default constructor available ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    Read the article

  • Primefaces: java.lang.ClassCastException: java.util.HashMap cannot be cast to ClassObject

    - by razegarra
    I have a problem with p:dataTable in Primefaces, I can not find the error. Class UsuarioAsig: public class UsuarioAsig { private BigDecimal codigopersona; private String nombre; private String paterno; private String materno; private String login; private String observacion; private String tipocontrol; private String externo; private String habilitado; private String nombreperfil; private BigDecimal codigousuario; ...get and set...} Class UsuarioAsigListaDataModel: public class UsuarioAsigListaDataModel extends ListDataModel<UsuarioAsig> implements SelectableDataModel<UsuarioAsig> { public UsuarioAsigListaDataModel(){} public UsuarioAsigListaDataModel(List<UsuarioAsig> data){super(data);} @Override public UsuarioAsig getRowData(String rowKey) { @SuppressWarnings("unchecked") List<UsuarioAsig> listaUsuarioAsigLectura = (List<UsuarioAsig>) getWrappedData(); for (UsuarioAsig usuarioAsig : listaUsuarioAsigLectura) { if (usuarioAsig.getCodigopersona().equals(rowKey)) { return usuarioAsig; } } return null; } @Override public Object getRowKey(UsuarioAsig usuarioAsig) { return usuarioAsig.getCodigopersona(); }} Controller UsuarioAsigController: @Controller("usuarioAsigController") @Scope(value = "session") public class UsuarioAsigController { private List<UsuarioAsig> listaUsuarioAsig; private HashMap<String, Object> selUsuarioAsig; private UsuarioAsigListaDataModel mediumUsuarioAsigModel; @Autowired UsuarioService usuarioService; ... public List<UsuarioAsig> getListaUsuarioAsig() { listaUsuarioAsig = usuarioService.selectAsig(); return listaUsuarioAsig; } public void setListaUsuarioAsig(List<UsuarioAsig> listaUsuarioAsig) { this.listaUsuarioAsig = listaUsuarioAsig; } public void setMediumUsuarioAsigModel(UsuarioAsigListaDataModel mediumUsuarioAsigModel) { this.mediumUsuarioAsigModel = mediumUsuarioAsigModel; } public UsuarioAsigListaDataModel getMediumUsuarioAsigModel() { listaUsuarioAsig = usuarioService.selectAsig(); mediumUsuarioAsigModel = new UsuarioAsigListaDataModel(listaUsuarioAsig); return mediumUsuarioAsigModel; } public void onRowSelect(SelectEvent event) { FacesMessage msg = new FacesMessage("Usuario seleccionado", ((UsuarioAsig) event.getObject()).getNombre()); FacesContext.getCurrentInstance().addMessage(null, msg); } } the error is generated when you click on one of the lines of datatable: asiginst.xhtml: <h:form id="form"> <p:growl id="msgs" showDetail="true" /> <p:dataTable id="usuarioAsigListaDataModel" var="usuarioAsig" value="#{usuarioAsigController.mediumUsuarioAsigModel}" rowKey="#{usuarioAsig.codigopersona}" selection="#{usuarioAsigController.selUsuarioAsig}" selectionMode="single" paginator="true" rows="10"> <p:ajax event="rowSelect" listener="#{usuarioAsigController.onRowSelect}" update=":form:msgs" /> <p:column headerText="Código" style="width:10%">#{usuarioAsig.codigopersona}</p:column> <p:column headerText="Nombre" style="width:32%">#{usuarioAsig.nombre}</p:column> <p:column headerText="Apellidos" style="width:32%">#{usuarioAsig.paterno} #{usuarioasig.materno}</p:column> <p:column headerText="Tipo Control" style="width:20%">#{usuarioAsig.tipocontrol}</p:column> <p:column headerText="Habilitado" style="width:6%">#{usuarioAsig.habilitado}</p:column> </p:dataTable> </h:form> THE ERROR IS GENERATED: WARNING: asiginst.xhtml @51,103 listener="#{usuarioAsigController.onRowSelect}": java.lang.ClassCastException: java.util.HashMap cannot be cast to com.datos.entidades.qry.UsuarioAsig javax.el.ELException: asiginst.xhtml @51,103 listener="#{usuarioAsigController.onRowSelect}": java.lang.ClassCastException: java.util.HashMap cannot be cast to com.datos.entidades.qry.UsuarioAsig at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111) at org.primefaces.behavior.ajax.AjaxBehaviorListenerImpl.processArgListener(AjaxBehaviorListenerImpl.java:69) at org.primefaces.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxBehaviorListenerImpl.java:56) at org.primefaces.event.SelectEvent.processListener(SelectEvent.java:40) at javax.faces.component.behavior.BehaviorBase.broadcast(BehaviorBase.java:102) at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:760) at javax.faces.component.UIData.broadcast(UIData.java:1071) at javax.faces.component.UIData.broadcast(UIData.java:1093) at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:409) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to com.datos.entidades.qry.UsuarioAsig at com.controller.UsuarioAsigController.onRowSelect(UsuarioAsigController.java:217) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.apache.el.parser.AstValue.invoke(AstValue.java:264) at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278) at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) ... 29 more

    Read the article

  • JNI, cast between jobect and jthrowable

    - by Dewfy
    Dear colleagues, I need raise an exception from C++ code. Raised exception must contain text and code of error. So common form: ThrowNew(jclass clazz, const char *msg) is not applicable. That is why I want create my own instance of java class: public class MyException extends Exception that contains one more property for code. But JNI interface has only declaration for Throw(jthrowable obj) Is it correct to cast instance of MyException to jthrowable ?

    Read the article

  • List to TreeSet conversion produces: "java.lang.ClassCastException: MyClass cannot be cast to java.l

    - by Chuck
    List<MyClass> myclassList = (List<MyClass>) rs.get(); TreeSet<MyClass> myclassSet = new TreeSet<MyClass>(myclassList); I don't understand why this code generates this: java.lang.ClassCastException: MyClass cannot be cast to java.lang.Comparable MyClass does not implement Comparable. I just want to use a Set to filter the unique elements of the List since my List contains unncessary duplicates.

    Read the article

  • Unable to cast lists with Reflection in C#

    - by DrLazer
    I am having a lot of trouble with Reflection in C# at the moment. The app I am writing allows the user to modify the attributes of certain objects using a config file. I want to be able to save the object model (users project) to XML. The function below is called in the middle of a foreach loop, looping through a list of objects that contain all the other objects in the project within them. The idea is, that it works recursively to translate the object model into XML. Dont worry about the call to "Unreal" that just modifes the name of the objects slightly if they contain certain words. private void ReflectToXML(object anObject, XmlElement parentElement) { Type aType = anObject.GetType(); XmlElement anXmlElement = m_xml.CreateElement(Unreal(aType.Name)); parentElement.AppendChild(anXmlElement); PropertyInfo[] pinfos = aType.GetProperties(); //loop through this objects public attributes foreach (PropertyInfo aInfo in pinfos) { //if the attribute is a list Type propertyType = aInfo.PropertyType; if ((propertyType.IsGenericType)&&(propertyType.GetGenericTypeDefinition() == typeof(List<>))) { List<object> listObjects = (aInfo.GetValue(anObject,null) as List<object>); foreach (object aListObject in listObjects) { ReflectToXML(aListObject, anXmlElement); } } //attribute is not a list else anXmlElement.SetAttribute(aInfo.Name, ""); } } If an object attributes are just strings then it should be writing them out as string attributes in the XML. If an objects attributes are lists, then it should recursively call "ReflectToXML" passing itself in as a parameter, thereby creating the nested structure I require that nicely reflect the object model in memory. The problem I have is with the line List<object> listObjects = (aInfo.GetValue(anObject,null) as List<object>); The cast doesn't work and it just returns null. While debugging I changed the line to object temp = aInfo.GetValue(anObject,null); slapped a breakpoint on it to see what "GetValue" was returning. It returns a "Generic list of objects" Surely I should be able to cast that? The annoying thing is that temp becomes a generic list of objects but because i declared temp as a singular object, I can't loop through it because it has no Enumerator. How can I loop through a list of objects when I only have it as a propertyInfo of a class? I know at this point I will only be saving a list of empty strings out anyway, but thats fine. I would be happy to see the structure save out for now. Thanks in advance

    Read the article

  • How to cast a STRING to a GUID

    - by GIbboK
    Hi, I need cast a String to a Guid. I am using this code but string myUserIdContent = ((Label)row.FindControl("uxUserIdDisplayer")).Text; Guid myGuidUserId = new Guid(myUserIdContent); // PROBLEM HERE MembershipUser mySelectedUser = Membership.GetUser(myGuidUserId); I receive this error Exception Details: System.FormatException: Unrecognized Guid format. ANy other ways to do it? thanks

    Read the article

  • C# cast Foo<Bar> to Foo<object>

    - by Michael
    Hi, does anyone know if it is possible to cast a generic type with a certain type parameter (e.g. Bar) to the same generic type with the type parameter being a base type of Bar (such as object in my case). And, if it is possible, how would it be done? What I want to do is have a collection of Foo but be able to add Foos with more specific type arguments. Thanks

    Read the article

  • Unable to cast object of type MyObject to type MyObject

    - by Robert W
    I have this scenario where a webservice method I'm consuming in C# returns a Business object, when calling the webservice method with the following code I get the exception "Unable to cast object of type ContactInfo to type ContactInfo" in the reference.cs class of the web reference Code: ContactInfo contactInfo = new ContactInfo(); Contact contact = new Contact(); contactInfo = contact.Load(this.ContactID.Value); Any help would be much appreciated.

    Read the article

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