Search Results

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

Page 11/31 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • QT: trouble with qobject_cast

    - by weevilo
    I have derived QGraphicsItem and QGraphicsScene classes. I want the items to be able to call scene() and get a derviedGraphicsItem * instead of a QGraphicsItem *, so I reimplemented QGraphicsScene::itemAt to return a derived pointer. DerivedItem* DerivedScene::itemAt( const QPointF &position, const QTransform &dt ) const { return qobject_cast< DerivedItem * >( QGraphicsScene::itemAt(position, dt) ); } I get the following error (Qt 4.6, GCC 4.4.3 on Ubuntut 10.4) scene.cpp: In member function ‘DerivedItem* DerivedScene::itemAt(qreal, qreal, const QTransform&) const’: scene.cpp:28: error: no matching function for call to ‘qobject_cast(QGraphicsItem*)’ I then noticed QGraphicsItem doesn't inherit QObject, so I made my derived QGraphicsItem class have multiple inheritance from QObject and QGraphicsItem, and after adding the Q_OBJECT macro and rebuilding the project I get the same error. Am I going about this the wrong way? I know it's supposed to be bad design to try to cast a parent class as a child, but in this case it seems like what I want, since my derived item class has new functionality and its objects need a way to call that new functionality on items around themselves, and asking the items scene object with itemAt() seems like the best way - but I need itemAt() to return a pointer of the right type. I can get around this by having the derived items cast the QGraphicsItem * returned by QGraphicsScene::itemAt() using dynamic_cast, but I don't really understand why that works and not qobject_cast, or the benefits or disadvantages to using dynamic_cast vs. qobject_cast.

    Read the article

  • NHibernate query with Projections.Cast to DateTime

    - by stiank81
    I'm experimenting with using a string for storing different kind of data types in a database. When I do queries I need to cast the strings to the right type in the query itself. I'm using .Net with NHibernate, and was glad to learn that there exists functionality for this. Consider the simple class: public class Foo { public string Text { get; set; } } I successfully use Projections.Cast to cast to numeric values, e.g. the following query correctly returns all Foos with an interger stored as int - between 1-10. var result = Session.CreateCriteria<Foo>() .Add(Restrictions.Between(Projections.Cast(NHibernateUtil.Int32, Projections.Property("Text")), 1, 10)) .List<Foo>(); Now if I try using this for DateTime I'm not able to make it work no matter what I try. Why?! var date = new DateTime(2010, 5, 21, 11, 30, 00); AddFooToDb(new Foo { Text = date.ToString() } ); // Will add it to the database... var result = Session .CreateCriteria<Foo>() .Add(Restrictions.Eq(Projections.Cast(NHibernateUtil.DateTime, Projections.Property("Text")), date)) .List<Foo>();

    Read the article

  • Cast to Extended Class in C# (dotnet 3.5<)

    - by csharpnoob
    Hi, i'm not sure if it's possible. I have a class car and a class mycar extended from class car. Class mycar has also a string list. Only difference. How can i cast now any car object to a mycar object without assigning all attributes each by hand. Like: Car car = new Car(); MyCar mcar = (MyCar) car; or MyCar mcar = new MyCar(car); or however i can extend car with own variables and don't have to do always Car car = new Car(); MyCar mcar = new MyCar(); mcar.name = car.name; mcar.xyz = car.xyz; ... Thanks.

    Read the article

  • Cast then check or check then cast?

    - by jamesrom
    Which method is regarded as best practice? Cast first? public string Describe(ICola cola) { var coke = cola as CocaCola; if (coke != null) { string result; // some unique coca-cola only code here. return result; } var pepsi = cola as Pepsi; if (pepsi != null) { string result; // some unique pepsi only code here. return result; } } Or should I check first, cast later? public string Describe(ICola cola) { if (cola is CocaCola) { coke = (CocaCola) cola; string result; // some unique coca-cola only code here. return result; } if (cola is Pepsi) { pepsi = (Pepsi) cola; string result; // some unique pepsi only code here. return result; } } Can you see any other way to do this?

    Read the article

  • Can't cast treeviewitem as treeviewitem in wpf

    - by phenevo
    Hi, I've got webservice asmx, and there are classes: Country public string Name {get;set;} public string Code {get;set;} public List<Area> Areas {get;set;} Area public string Name {get;set;} public string Code {get;set;} public List<Regions> Provinces {get;set;} Provinces public string Name {get;set;} public string Code {get;set;} I bind it to mz TreeView WPF: Country[] items = new MyService().GetListOfCountries(); structureTree.ItemsSource = items; Code of myTree: <UserControl x:Class="ObjectsAndZonesSimpleTree" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" <Grid> <StackPanel Name="stackPanel1"> <GroupBox Header="Choose" Height="354" Name="groupBox1" Width="Auto"> <TreeView Name="structureTree" SelectedItemChanged="structureTree_SelectedItemChanged" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding}" Height="334" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Visible" Width="Auto" PreviewMouseRightButtonUp="structureTree_PreviewMouseRightButtonUp" FontFamily="Verdana" FontSize="12" BorderThickness="1" MinHeight="0" Padding="1" Cursor="Hand" Margin="-1"> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type MyService:Country}" ItemsSource="{Binding Path=ListOfRegions}"> <StackPanel Orientation="Horizontal"> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=Name}"/> </StackPanel> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type MyService:Region}" ItemsSource="{Binding Path=Provinces}"> <StackPanel Orientation="Horizontal"> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=Name}"/> </StackPanel> </HierarchicalDataTemplate> <DataTemplate DataType="{x:Type MyService:Province}" ItemsSource="{Binding Path=ListOfCities}"> <StackPanel Orientation="Horizontal"> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=Name}"/> </StackPanel> </DataTemplate> </TreeView.Resources> </TreeView> </GroupBox> </StackPanel> </Grid> </UserControl> This gives me null: private void structureTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { TreeViewItem treeViewItem = structureTree.SelectedItem as TreeViewItem; }

    Read the article

  • Avoiding unsafe cast for generic situation involving runtime passing of class

    - by Bart van Heukelom
    public class AutoKeyMap<K,V> { public interface KeyGenerator<K> { public K generate(); } private KeyGenerator<K> generator; public AutoKeyMap(Class<K> keyType) { // WARNING: Unchecked cast from AutoKeyMap.IntKeyGen to AutoKeyMap.KeyGenerator<K> if (keyType == Integer.class) generator = (KeyGenerator<K>) new IntKeyGen(); else throw new RuntimeException("Cannot generate keys for " + keyType); } public void put(V value) { K key = generator.generate(); ... } private static class IntKeyGen implements KeyGenerator<Integer> { private final AtomicInteger ai = new AtomicInteger(1); @Override public Integer generate() { return ai.getAndIncrement(); } } } In the code sample above, what is the correct way to prevent the given warning, without adding a @SuppressWarnings, if any?

    Read the article

  • How do I work around the GCC "error: cast from ‘SourceLocation*’ to ‘int’ loses precision" error when compiling cmockery.c?

    - by Daryl Spitzer
    I need to add unit tests using Cmockery to an existing build environment that uses as hand-crafted Makefile. So I need to figure out how to build cmockery.c (without automake). When I run: g++ -DHAVE_CONFIG_H -DPIC -I ../cmockery-0.1.2 -I /usr/include/malloc -c ../cmockery-0.1.2/cmockery.c -o obj/cmockery.o I get a long list of errors like this: ../cmockery-0.1.2/cmockery.c: In function ‘void initialize_source_location(SourceLocation*)’: ../cmockery-0.1.2/cmockery.c:248: error: cast from ‘SourceLocation*’ to ‘int’ loses precision Here are lines 247:248 of cmockery.c: static void initialize_source_location(SourceLocation * const location) { assert_true(location); assert_true is defined on line 154 of cmockery.h: #define assert_true(c) _assert_true((int)(c), #c, __FILE__, __LINE__) So the problem (as the error states) is GCC doesn't like the cast from ‘SourceLocation*’ to ‘int’. I can build Cmockery using ./configure and make (on Linux, and on Mac OS X if I export CFLAGS=-I/usr/include/malloc first), without any errors. I've tried looking at the command-line that compiles cmockery.c when I run make (after ./configure): gcc -DHAVE_CONFIG_H -I. -I. -I./src -I./src -Isrc/google -I/usr/include/malloc -MT libcmockery_la-cmockery.lo -MD -MP -MF .deps/libcmockery_la-cmockery.Tpo -c src/cmockery.c -fno-common -DPIC -o .libs/libcmockery_la-cmockery.o ...but I don't see any options that might work around this error. In "error: cast from 'void*' to 'int' loses precision", I see I could change (int) in cmockery.h to (intptr_t). And I've confirmed that works. But since I can build Cmockery with ./configure and make, there must be a way to get it to build without modifying the source.

    Read the article

  • Performance penalty of typecasting and boxing/unboxing types in C# when storing generic values

    - by kitsune
    I have a set-up similar to WPF's DependencyProperty and DependencyObject system. My properties however are generic. A BucketProperty has a static GlobalIndex (defined in BucketPropertyBase) which tracks all BucketProperties. A Bucket can have many BucketProperties of any type. A Bucket saves and gets the actual values of these BucketProperties... now my question is, how to deal with the storage of these values, and what is the penalty of using a typecasting when retrieving them? I currently use an array of BucketEntries that save the property values as simple objects. Is there any better way of saving and returning these values? Beneath is a simpliefied version: public class BucketProperty<T> : BucketPropertyBase { } public class Bucket { private BucketEntry[] _bucketEntries; public void SaveValue<T>(BucketProperty<T> property, T value) { SaveBucketEntry(property.GlobalIndex, value) } public T GetValue<T>(BucketProperty<T> property) { return (T)FindBucketEntry(property.GlobalIndex).Value; } } public class BucketEntry { private object _value; private uint _index; public BucketEntry(uint globalIndex, object value) { ... } }

    Read the article

  • For Nvarchar(Max) I am only getting 4000 characters in TSQL?

    - by Malcolm
    Hi, This is for SS 2005. Why I am i only getting 4000 characters and not 8000? It truncates the string @SQL1 at 4000. ALTER PROCEDURE sp_AlloctionReport( @where NVARCHAR(1000), @alldate NVARCHAR(200), @alldateprevweek NVARCHAR(200)) AS DECLARE @SQL1 NVARCHAR(Max) SET @SQL1 = 'SELECT DISTINCT VenueInfo.VenueID, VenueInfo.VenueName, VenuePanels.PanelID, VenueInfo.CompanyName, VenuePanels.ProductCode, VenuePanels.MF, VenueInfo.Address1, VenueInfo.Address2, '' As AllocationDate, '' As AbbreviationCode, VenueInfo.Suburb, VenueInfo.Route, VenueInfo.ContactFirstName, VenueInfo.ContactLastName, VenueInfo.SuitableTime, VenueInfo.OldVenueName, VenueCategories.Category, VenueInfo.Phone, VenuePanels.Location, VenuePanels.Comment, [VenueCategories].[Category] + '' Allocations'' AS ReportHeader, ljs.AbbreviationCode AS PrevWeekCampaign FROM (((VenueInfo INNER JOIN VenuePanels ON VenueInfo.VenueID = VenuePanels.VenueID) INNER JOIN VenueCategories ON VenueInfo.CategoryID = VenueCategories.CategoryID) LEFT JOIN (SELECT CampaignProductions.AbbreviationCode, VenuePanels.PanelID, CampaignAllocations.AllocationDate FROM (((VenueInfo INNER JOIN VenuePanels ON VenueInfo.VenueID=VenuePanels.VenueID) INNER JOIN CampaignAllocations ON VenuePanels.PanelID=CampaignAllocations.PanelID) INNER JOIN CampaignProductions ON CampaignAllocations.CampaignID=CampaignProductions.CampaignID) INNER JOIN VenueCategories ON VenueInfo.CategoryID=VenueCategories.CategoryID WHERE ' + @alldateprevweek + ') ljs ON VenuePanels.PanelID = ljs.PanelID) INNER JOIN (SELECT VenueInfo.VenueID, VenuePanels.PanelID, VenueInfo.VenueName, VenueInfo.CompanyName, VenuePanels.ProductCode, VenuePanels.MF, VenueInfo.Address1, VenueInfo.Address2, CampaignAllocations.AllocationDate, CampaignProductions.AbbreviationCode, VenueInfo.Suburb, VenueInfo.Route, VenueInfo.ContactFirstName, VenueInfo.ContactLastName, VenueInfo.SuitableTime, VenueInfo.OldVenueName, VenueCategories.Category, VenueInfo.Phone, VenuePanels.Location, VenuePanels.Comment, [Category] + '' Allocations'' AS ReportHeader, ljs2.AbbreviationCode AS PrevWeekCampaign FROM ((((VenueInfo INNER JOIN VenuePanels ON VenueInfo.VenueID = VenuePanels.VenueID) INNER JOIN CampaignAllocations ON VenuePanels.PanelID = CampaignAllocations.PanelID) INNER JOIN CampaignProductions ON CampaignAllocations.CampaignID = CampaignProductions.CampaignID) INNER JOIN VenueCategories ON VenueInfo.CategoryID = VenueCategories.CategoryID) LEFT JOIN (SELECT CampaignProductions.AbbreviationCode, VenuePanels.PanelID, CampaignAllocations.AllocationDate FROM (((VenueInfo INNER JOIN VenuePanels ON VenueInfo.VenueID=VenuePanels.VenueID) INNER JOIN CampaignAllocations ON VenuePanels.PanelID=CampaignAllocations.PanelID) INNER JOIN CampaignProductions ON CampaignAllocations.CampaignID=CampaignProductions.CampaignID) INNER JOIN VenueCategories ON VenueInfo.CategoryID=VenueCategories.CategoryID WHERE ' + @alldateprevweek + ') ljs2 ON VenuePanels.PanelID = ljs2.PanelID WHERE ' + @alldate + ' AND ' + @where + ') ljs3 ON VenueInfo.VenueID = ljs3.VenueID WHERE (((VenuePanels.PanelID)<>ljs3.[PanelID] And (VenuePanels.PanelID) Not In (SELECT PanelID FROM CampaignAllocations WHERE ' + @alldateprevweek + ')) AND ' + @where + ') UNION ALL SELECT VenueInfo.VenueID, VenueInfo.VenueName, VenuePanels.PanelID, VenueInfo.CompanyName, VenuePanels.ProductCode, VenuePanels.MF, VenueInfo.Address1, VenueInfo.Address2, CampaignAllocations.AllocationDate, CampaignProductions.AbbreviationCode, VenueInfo.Suburb, VenueInfo.Route, VenueInfo.ContactFirstName, VenueInfo.ContactLastName, VenueInfo.SuitableTime, VenueInfo.OldVenueName, VenueCategories.Category, VenueInfo.Phone, VenuePanels.Location, VenuePanels.Comment, [Category] + '' Allocations'' AS ReportHeader, ljs.AbbreviationCode AS PrevWeekCampaign FROM ((((VenueInfo INNER JOIN VenuePanels ON VenueInfo.VenueID = VenuePanels.VenueID) INNER JOIN CampaignAllocations ON VenuePanels.PanelID = CampaignAllocations.PanelID) INNER JOIN CampaignProductions ON CampaignAllocations.CampaignID = CampaignProductions.CampaignID) INNER JOIN VenueCategories ON VenueInfo.CategoryID = VenueCategories.CategoryID) LEFT JOIN (SELECT CampaignProductions.AbbreviationCode, VenuePanels.PanelID, CampaignAllocations.AllocationDate FROM (((VenueInfo INNER JOIN VenuePanels ON VenueInfo.VenueID=VenuePanels.VenueID) INNER JOIN CampaignAllocations ON VenuePanels.PanelID=CampaignAllocations.PanelID) INNER JOIN CampaignProductions ON CampaignAllocations.CampaignID=CampaignProductions.CampaignID) INNER JOIN VenueCategories ON VenueInfo.CategoryID=VenueCategories.CategoryID WHERE ' + @alldateprevweek + ') ljs ON VenuePanels.PanelID = ljs.PanelID WHERE ' + @alldate + ' AND ' + @where Select @SQL1

    Read the article

  • Help with InvalidCastException

    - by Robert
    I have a gridview and, when a record is double-clicked, I want it to open up a new detail-view form for that particular record. As an example, I have created a Customer class: using System; using System.Data; using System.Configuration; using System.Collections.Generic; using System.ComponentModel; using System.Data.SqlClient; using System.Collections; namespace SyncTest { #region Customer Collection public class CustomerCollection : BindingListView<Customer> { public CustomerCollection() : base() { } public CustomerCollection(List<Customer> customers) : base(customers) { } public CustomerCollection(DataTable dt) { foreach (DataRow oRow in dt.Rows) { Customer c = new Customer(oRow); this.Add(c); } } } #endregion public class Customer : INotifyPropertyChanged, IEditableObject, IDataErrorInfo { private string _CustomerID; private string _CompanyName; private string _ContactName; private string _ContactTitle; private string _OldCustomerID; private string _OldCompanyName; private string _OldContactName; private string _OldContactTitle; private bool _Editing; private string _Error = string.Empty; private EntityStateEnum _EntityState; private Hashtable _PropErrors = new Hashtable(); public event PropertyChangedEventHandler PropertyChanged; private void FirePropertyChangeNotification(string propName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } public Customer() { this.EntityState = EntityStateEnum.Unchanged; } public Customer(DataRow dr) { //Populates the business object item from a data row this.CustomerID = dr["CustomerID"].ToString(); this.CompanyName = dr["CompanyName"].ToString(); this.ContactName = dr["ContactName"].ToString(); this.ContactTitle = dr["ContactTitle"].ToString(); this.EntityState = EntityStateEnum.Unchanged; } public string CustomerID { get { return _CustomerID; } set { _CustomerID = value; FirePropertyChangeNotification("CustomerID"); } } public string CompanyName { get { return _CompanyName; } set { _CompanyName = value; FirePropertyChangeNotification("CompanyName"); } } public string ContactName { get { return _ContactName; } set { _ContactName = value; FirePropertyChangeNotification("ContactName"); } } public string ContactTitle { get { return _ContactTitle; } set { _ContactTitle = value; FirePropertyChangeNotification("ContactTitle"); } } public Boolean IsDirty { get { return ((this.EntityState != EntityStateEnum.Unchanged) || (this.EntityState != EntityStateEnum.Deleted)); } } public enum EntityStateEnum { Unchanged, Added, Deleted, Modified } void IEditableObject.BeginEdit() { if (!_Editing) { _OldCustomerID = _CustomerID; _OldCompanyName = _CompanyName; _OldContactName = _ContactName; _OldContactTitle = _ContactTitle; } this.EntityState = EntityStateEnum.Modified; _Editing = true; } void IEditableObject.CancelEdit() { if (_Editing) { _CustomerID = _OldCustomerID; _CompanyName = _OldCompanyName; _ContactName = _OldContactName; _ContactTitle = _OldContactTitle; } this.EntityState = EntityStateEnum.Unchanged; _Editing = false; } void IEditableObject.EndEdit() { _Editing = false; } public EntityStateEnum EntityState { get { return _EntityState; } set { _EntityState = value; } } string IDataErrorInfo.Error { get { return _Error; } } string IDataErrorInfo.this[string columnName] { get { return (string)_PropErrors[columnName]; } } private void DataStateChanged(EntityStateEnum dataState, string propertyName) { //Raise the event if (PropertyChanged != null && propertyName != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } //If the state is deleted, mark it as deleted if (dataState == EntityStateEnum.Deleted) { this.EntityState = dataState; } if (this.EntityState == EntityStateEnum.Unchanged) { this.EntityState = dataState; } } } } Here is my the code for the double-click event: private void customersDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { Customer oCustomer = (Customer)customersBindingSource.CurrencyManager.List[customersBindingSource.CurrencyManager.Position]; CustomerForm oForm = new CustomerForm(); oForm.NewCustomer = oCustomer; oForm.ShowDialog(this); oForm.Dispose(); oForm = null; } Unfortunately, when this code runs, I receive an InvalidCastException error stating "Unable to cast object to type 'System.Data.DataRowView' to type 'SyncTest.Customer'". This error occurs on the very first line of that event: Customer oCustomer = (Customer)customersBindingSource.CurrencyManager.List[customersBindingSource.CurrencyManager.Position]; What am I doing wrong?... and what can I do to fix this? Any help is greatly appreciated. Thanks!

    Read the article

  • Base class -> Derived class and vice-versa conversions in C++

    - by Ivan Nikolaev
    Hi! I have the following example code: #include <iostream> #include <string> using namespace std; class Event { public: string type; string source; }; class KeyEvent : public Event { public: string key; string modifier; }; class MouseEvent : public Event { public: string button; int x; int y; }; void handleEvent(KeyEvent e) { if(e.key == "ENTER") cout << "Hello world! The Enter key was pressed ;)" << endl; } Event generateEvent() { KeyEvent e; e.type = "KEYBOARD_EVENT"; e.source = "Keyboard0"; e.key = "SPACEBAR"; e.modifier = "none"; return e; } int main() { KeyEvent e = generateEvent(); return 0; } I can't compile it, G++ throws an error of kind: main.cpp: In function 'int main()': main.cpp:47:29: error: conversion from 'Event' to non-scalar type 'KeyEvent' requested I know that the error is obvious for C++ guru's, but I can't understand why I can't do the conversion from base class object to derived one. Can someone suggest me the solution of the problem that I have? Thx in advice

    Read the article

  • .NET Type Conversion Issue: Simple but difficult

    - by jaderanderson
    Well, the question is kinda simple. I have a object defined as: public class FullListObject : System.Collections.ArrayList, IPagedCollection And when i try to: IPagedCollection pagedCollection = (IPagedCollection)value; It don't work... value is a FullListObject... this is my new code trying to get around a issue with the "is" operator. When the system tests (value is IPagedCollection) it never gets true for FullListObject. How to cast the object to another object with a interface type?

    Read the article

  • VB.NET invalid cast exception

    - by user127147
    Hi there, I have a simple application to store address details and edit them. I have been away from VB for a few years now and need to refreash my knowledge while working to a tight deadline. I have a general Sub responsible for displaying a form where user can add contact details (by pressing button add) and edit them (by pressing button edit). This sub is stored in a class Contact. The way it is supposed to work is that there is a list with all the contacts and when new contact is added a new entry is displayed. If user wants to edit given entry he or she selects it and presses edit button Public Sub Display() Dim C As New Contact C.Cont = InputBox("Enter a title for this contact.") C.Fname = frmAddCont.txtFName.Text C.Surname = frmAddCont.txtSName.Text C.Address = frmAddCont.txtAddress.Text frmStart.lstContact.Items.Add(C.Cont.ToString) End Sub I call it from the form responsible for adding new contacts by Dim C As New Contact C.Display() and it works just fine. However when I try to do something similar using the edit button I get errors - "Unable to cast object of type 'System.String' to type 'AddressBook.Contact'." Dim C As Contact If lstContact.SelectedItem IsNot Nothing Then C = lstContact.SelectedItem() C.Display() End If I think it may be something simple however I wasn't able to fix it and given short time I have I decided to ask for help here. Thank you

    Read the article

  • What is CDbl doing?

    - by Dan Tao
    I had until recently been under the impression that the CDbl(x) operation in VB.NET was essentially a cast (i.e., the VB equivalent of (double)x in C#); but a recent discovery has revealed that this is not the case. If I have this string: Dim s As String = "12345.12345-" And I do this: Dim d As Double = CDbl(s) d will be set to the value -12345.12345! Now, don't get me wrong, this is kind of convenient in my particular scenario; but I have to admit I'm confused as to why this works. In particular, I'm confused because: Double.Parse does not work with the above input. Double.TryParse does not work. Convert.ToDouble does not work. How is CDbl so clever?

    Read the article

  • Use of IsAssignableFrom and "is" keyword in C#

    - by fearofawhackplanet
    While trying to learn Unity, I keep seeing the following code for overriding GetControllerInstance in MVC: if(!typeof(IController).IsAssignableFrom(controllerType)) { ... } this seems to me a pretty convoluted way of basically writing if(controllerType is IController) { ... } I appreciate there are subtle differences between is and IsAssignableFrom, ie IsAssignableFrom doesn't include cast conversions, but I'm struggling to understand the implication of this difference in practical scenarios. When is it imporantant to choose IsAssignableFrom over is? What difference would it make in the GetControllerExample? if (!typeof(IController).IsAssignableFrom(controllerType)) throw new ArgumentException(...); return _container.Resolve(controllerType) as IController;

    Read the article

  • Generic List<T> as IEnumerable<object>

    - by Avi
    I'm trying to do cast a List to an IEnumerable, so I can verify that different lists are not null or empty: Suppose myList is a List < T . Then in the caller code I wanted: Validator.VerifyNotNullOrEmpty(myList as IEnumerable<object>, @"myList", @"ClassName.MethodName"); The valdiating code would be: public static void VerifyNotNullOrEmpty(IEnumerable<object> theIEnumerable, string theIEnumerableName, string theVerifyingPosition) { string errMsg = theVerifyingPosition + " " + theIEnumerableName; if (theIEnumerable == null) { errMsg += @" is null"; Debug.Assert(false); throw new ApplicationException(errMsg); } else if (theIEnumerable.Count() == 0) { errMsg += @" is empty"; Debug.Assert(false); throw new ApplicationException(errMsg); } } However, this doens't work. It compiles, but theIEnumerable is null! Why?

    Read the article

  • "possible loss of precision" is Java going crazy or I'm missing something?

    - by Lo'oris
    I'm getting a "loss of precision" error when there should be none, AFAIK. this is an instance variable: byte move=0; this happens in a method of this class: this.move=(this.move<<4)|(byte)(Guy.moven.indexOf("left")&0xF); move is a byte, move is still a byte, and the rest is being cast to a byte. I get this error: [javac] /Users/looris/Sviluppo/dumdedum/client/src/net/looris/android/toutry/Guy.java:245: possible loss of precision [javac] found : int [javac] required: byte [javac] this.move=(this.move<<4)|(byte)(Guy.moven.indexOf("left")&0xF); [javac] ^ I've tried many variations but I still get the same error. I'm now clueless.

    Read the article

  • Modifying a const through a non-const pointer

    - by jasonline
    I'm a bit confused what happened in the following code: const int e = 2; int* w = ( int* ) &e; // (1) cast to remove const-ness *w = 5; // (2) cout << *w << endl; // (3) outputs 5 cout << e << endl; // (4) outputs 2 cout << "w = " << w << endl; // (5) w points to the address of e cout << "&e = " << &e << endl; In (1), w points to the address of e. In (2), that value was changed to 5. However, when the values of *w and e were displayed, their values are different. But if you print value of w pointer and &e, they have the same value/address. How come e still contained 2, even if it was changed to 5? Were they stored in a separate location? Or a temporary? But how come the value pointed by w is still the address of e?

    Read the article

  • sqrt(int_value + 0.0) -- Does it have a purpose?

    - by Earlz
    Hello, while doing some homework in my very strange C++ book, which I've been told before to throw away, had a very peculiar code segment. I know homework stuff always throws in extra "mystery" to try to confuse you like indenting 2 lines after a single-statement for-loop. But this one I'm confused on because it seems to serve some real-purpose. basically it is like this: int counter=10; ... if(pow(floor(sqrt(counter+0.0)),2) == counter) ... I'm interested in this part especially: sqrt(counter+0.0) Is there some purpose to the +0.0? Is this the poormans way of doing a static cast to a double? Does this avoid some compiler warning on some compiler I do not use? The entire program printed the exact same thing and compiled without warnings on g++ whenever I left out the +0.0 part. Maybe I'm not using a weird enough compiler? Edit: Also, does gcc just break standard and not make an error for Ambiguous reference since sqrt can take 3 different types of parameters? [earlz@EarlzBeta-~/projects/homework1] $ cat calc.cpp #include <cmath> int main(){ int counter=0; sqrt(counter); } [earlz@EarlzBeta-~/projects/homework1] $ g++ calc.cpp /usr/lib/libstdc++.so.47.0: warning: strcpy() is almost always misused, please use strlcpy() /usr/lib/libstdc++.so.47.0: warning: strcat() is almost always misused, please use strlcat() [earlz@EarlzBeta-~/projects/homework1] $

    Read the article

  • How to access generic property without knowing the closed generic type

    - by Martin Booka Weser
    I have a generic Type as follows public class TestGeneric<T> { public T Data { get; set; } public TestGeneric(T data) { this.Data = data; } } If i have now an object (which is coming from some external source) from which i know that it's type is of some closed TestGeneric<, but i don't know the TypeParameter T. Now I need to access the Data of my object. Problem is that i can't cast the object, since i don't know exactly to which closed TestGeneric. I use // thx to http://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class private static bool IsSubclassOfRawGeneric(Type rawGeneric, Type subclass) { while (subclass != typeof(object)) { var cur = subclass.IsGenericType ? subclass.GetGenericTypeDefinition() : subclass; if (rawGeneric == cur) { return true; } subclass = subclass.BaseType; } return false; } to make sure, my object is of the generic type. The code in question is as follows: public static void Main() { object myObject = new TestGeneric<string>("test"); // or from another source if (IsSubclassOfRawGeneric(typeof(TestGeneric<>), myObject.GetType())) { // the following gives an InvalidCastException // var data = ((TestGeneric<object>)myObject).Data; // if i try to access the property with reflection // i get an InvalidOperationException var dataProperty = typeof(TestGeneric<>).GetProperty("Data"); object data = dataProperty.GetValue(myObject, new object[] { }); } } I need the Data regardless of its type (well, if i could ask for its type using GetType() would be fine, but not necessary) since i just want to dump it in xml using ToString(). Any suggestions? Thanx.

    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

  • How to determine visibility in 2D

    - by Jack
    Hello, I'm developing an AI sandbox and I would like to calculate what every living entity can see. The rule is to simply hide what's behind the edges of the shapes from the point of view of the entity. The image clarifies everything: I need it either as an input to the artificial intelligence either graphically, to show it for a specific entity while it moves.. Any cool ideas?

    Read the article

  • How Can I Check an Object to See its Type and Return A Casted Object

    - by Russ Bradberry
    I have method to which I pass an object. In this method I check it's type and depending on the type I do something with it and return a Long. I have tried every which way I can think of to do this and I always get several compiler errors telling me it expects a certain object but gets another. Can someone please explain to me what I am doing wrong and guide me in the right direction? What I have tried thus far is below: override def getInteger(obj:Object) = { if (obj.isInstanceOf[Object]) null else if (obj.isInstanceOf[Number]) (obj:Number).longValue() else if (obj.isInstanceOf[Boolean]) if (obj:Boolean) 1 else 0 else if (obj.isInstanceOf[String]) if ((obj:String).length == 0 | (obj:String) == "null") null else try { Long.parse(obj:String) } catch { case e: Exception => throw new ValueConverterException("value \"" + obj.toString() + "\" of type " + obj.getClass().getName() + " is not convertible to Long") } }

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >