Search Results

Search found 6357 results on 255 pages for 'generic relations'.

Page 42/255 | < Previous Page | 38 39 40 41 42 43 44 45 46 47 48 49  | Next Page >

  • Casting to generic type in Java doesn't raise ClassCastException?

    - by Kip
    I have come across a strange behavior of Java that seems like a bug. Is it? Casting an Object to a generic type (say, K) does not throw a ClassCastException even if the object is not an instance of K. Here is an example: import java.util.*; public final class Test { private static<K,V> void addToMap(Map<K,V> map, Object ... vals) { for(int i = 0; i < vals.length; i += 2) map.put((K)vals[i], (V)vals[i+1]); //Never throws ClassCastException! } public static void main(String[] args) { Map<String,Integer> m = new HashMap<String,Integer>(); addToMap(m, "hello", "world"); //No exception System.out.println(m.get("hello")); //Prints "world", which is NOT an Integer!! } }

    Read the article

  • How do I improve the efficiency of the queries executed by this generic Linq-to-SQL data access clas

    - by Lee D
    Hi all, I have a class which provides generic access to LINQ to SQL entities, for example: class LinqProvider<T> //where T is a L2S entity class { DataContext context; public virtual IEnumerable<T> GetAll() { return context.GetTable<T>(); } public virtual T Single(Func<T, bool> condition) { return context.GetTable<T>().SingleOrDefault(condition); } } From the front end, both of these methods appear to work as you would expect. However, when I run a trace in SQL profiler, the Single method is executing what amounts to a SELECT * FROM [Table], and then returning the single entity that meets the given condition. Obviously this is inefficient, and is being caused by GetTable() returning all rows. My question is, how do I get the query executed by the Single() method to take the form SELECT * FROM [Table] WHERE [condition], rather than selecting all rows then filtering out all but one? Is it possible in this context? Any help appreciated, Lee

    Read the article

  • What should I name my files with generic class definitions?

    - by Tomas Lycken
    I'm writing a couple of classes that all have generic type arguments, but I need to overload the classes because I need a different number of arguments in different scenarios. Basically, I have public class MyGenericClass<T> { ... } public class MyGenericClass<T, K> { ... } public class MyGenericClass<T, K, L> { ... } // it could go on forever, but it won't... I want them all in the same namespace, but in one source file per class. What should I name the files? Is there a best practice?

    Read the article

  • Django: way to test what class a generic relation content_object is?

    - by bitbutter
    In my project I have a class, NewsItem. Instances of NewsItem act like a wrapper. They can be associated with either an ArtWork instance, or an Announcement instance. Here's how the NewsItem model looks: class NewsItem(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') date = models.DateTimeField(default=datetime.datetime.now,) class Meta: ordering = ('-date',) def __unicode__(self): return (self.title()) In a template I'm dealing with a NewsItem instance, and would like to output a certain bunch of html it it's 'wrapping' an Artwork instance, and a different bunch of html if it's wrapping an Announcement instance. Could someone explain how I can write a conditional to test for this? My first naive try looked like this: {% if news_item.content_object.type=='Artwork' %}do this{% else %}do that{% endif %}

    Read the article

  • Insert into a generic dictionary with possibility of duplicate keys?

    - by Chris Clark
    Is there any reason to favor one of these approaches over the other when inserting into a generic dictionary with the possibility of a key conflict? I'm building an in-memory version of a static collection so in the case of a conflict it doesn't matter whether the old or new value is used. If Not mySettings.ContainsKey(key) Then mySettings.Add(key, Value) End If Versus mySettings(key) = Value And then of course there is this, which is obviously not the right approach: Try mySettings.Add(key, Value) Catch End Try Clearly the big difference here is that the first and second approaches actually do different things, but in my case it doesn't matter. It seems that the second approach is cleaner, but I'm curious if any of you .net gurus have any deeper insight. Thanks!

    Read the article

  • Best way to test if a generic type is a string? (c#)

    - by Rex M
    I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1: T createDefault() { if(typeof(T).IsValueType) { return default(T); } else { return Activator.CreateInstance<T>(); } } Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is: T createDefault() { if(typeof(T).IsValueType || typeof(T).FullName == "System.String") { return default(T); } else { return Activator.CreateInstance<T>(); } } But this feels like a kludge. Is there a nicer way to handle the string case?

    Read the article

  • C# How to check if a class implements generic interface ?

    - by PaN1C_Showt1Me
    How to get generic interface type for an instance ? Suppose this code: interface IMyInterface<T> { T MyProperty { get; set; } } class MyClass : IMyInterface<int> { #region IMyInterface<T> Members public int MyProperty { get; set; } #endregion } MyClass myClass = new MyClass(); /* returns the interface */ Type[] myinterfaces = myClass.GetType().GetInterfaces(); /* returns null */ Type myinterface = myClass.GetType().GetInterface(typeof(IMyInterface<int>).FullName);

    Read the article

  • Best practices about creating a generic object dictionary in C#? Is this bad?

    - by JimDaniel
    For clarity I am using C# 3.5/Asp.Net MVC 2 Here is what I have done: I wanted the ability to add/remove functionality to an object at run-time. So I simply added a generic object dictionary to my class like this: public Dictionary<int, object> Components { get; set; } Then I can add/remove any kind of .Net object into this dictionary at run-time. To insert an object I do something like this: var tag = new Tag(); myObject.Components.Add((int)Types.Components.Tag, tag); Then to retrieve I just do this: if(myObject.Components.ContainsKey((int)Types.Components.Tag)) { var tag = myObject.Components[(int)Types.Components.Tag] as Tag; if(tag != null) { //do stuff } } Somehow I feel sneaky doing this. It works okay, but I am wondering what you guys think about it as a best practice. Thanks for your input, Daniel

    Read the article

  • What is a great resource for learning about the implementation details of .NET generic collections?

    - by Jimmy W
    Hi all, I'm interested in understanding the underlying implementation details of generic collections in .NET. What I have in mind are details such as how the collections are stored, how each member of a collection is accessed by the CLR, etc. For collections that are analogous to traditional data structures, such as LinkedList and Dictionary, I think I have an understanding of what's going on underneath. However, I'm not as certain about collections like List (how is set up such that it is both indexable and expandable?) and SortedList, so any leads as to what I could look up to learn more about them would be greatly appreciated.

    Read the article

  • How to convert value of Generic Type Argument to a concrete type?

    - by Aleksey Bieneman
    I am trying to convert the value of the generic type parameter T value into integer after making sure that T is in fact integer: public class Test { void DoSomething<T>(T value) { var type = typeof(T); if (type == typeof(int)) { int x = (int)value; // Error 167 Cannot convert type 'T' to 'int' int y = (int)(object)value; // works though boxing and unboxing } } } Although it works through boxing and unboxing, this is an additional performance overhead and i was wandering if there's a way to do it directly. Thank you!

    Read the article

  • How can i sort DESC and ASC in list generic?

    - by Phsika
    How can I sort DESC and ASC in a generic list? With LINQ and without LINQ ? I'm using vs 2008. class Program { static void Main(string[] args) { List<int> li = new List<int>(); li.Add(456); li.Add(123); li.Add(12345667); li.Add(0); li.Add(1); li.Sort(); foreach (int item in li) { Console.WriteLine(item.ToString()+"\n"); } Console.ReadKey(); } }

    Read the article

  • is this possible: c# collection of Type with constrains, or collection of generic type?

    - by Jon
    I'm trying to store types in a collection, so that i can later instantiate objects of the types in the collection. But I'm not sure how to do this the best way. What i have so far: List<Type> list = new List<Type>(); list.Add(typeof(MyClass)); var obj = (MyClass)Activator.CreateInstance(list[0]); I would like to have some constrains on the Type, or better yet, just a generic type in the collection instead of an instantiated Type object. Is this possible?

    Read the article

  • Java generic function for performing calculations on integer, on double?

    - by Daniel
    Is this possible? Surely if you passed in a double, any sort of function implementation code which casts an object to an Integer would not be able to work unless the cast 'Integer' was specifically used? I have a function like: public static void increment(Object o){ Integer one = (Integer)o; system.out.println(one++); } I cant see how this could be made generic for a double? I tried public static <E> void increment(E obj){ E one = (E)o; system.out.println(one++); } but it didn't like it?

    Read the article

  • Generic type parameter naming convention for Java (with multiple chars)?

    - by chaper29
    In some interfaces i wrote I'd like to name generic type parameter with more than one character to make the code more readable. Something like.... Map<Key,Value> Instead of this... Map<K,V> But when it comes to methods, the type-parameters look like java-classes which is also confusing. public void put(Key key, Value value) This seems like Key and Value are classes. I found or thought of some notations, but nothing like a convention from sun or a general best-practice. Alternatives i guesed of or found... Map<KEY,VALUE> Map<TKey,TValue>

    Read the article

  • Are static members of a generic class tied to the specific instance?

    - by mafutrct
    This is more of a documentation than a real question. I noticed the principle it is not described on SO yet (did I miss it?), so here goes: Imagine a generic class that contains a static member: class Foo<T> { public static int member; } Is there a new instance of the member for each specific class, or is there only a single instance for all Foo-type classes? It can easily be verified by code like this: Foo<int>.member = 1; Foo<string>.member = 2; Console.WriteLine (Foo<int>.member); What is the result, and where is this behavior documented?

    Read the article

  • Sendmail + m4 - problem converting mc files into cf

    - by zbigh
    Hi I'm currently trying to configure sendmail fo the first time and setup a mail server on a small embedded computer ( running a custom linux distribution ). I'm having an issue with the m4 macros: I'm trying to convert this: VERSIONID(`$Id: generic-linux.mc,v 8.1 1999/09/24 22:48:05 gshapiro Exp $') OSTYPE(linux)dnl DOMAIN(generic)dnl define(HELPFILE, `/etc/mail/helpfile') FEATURE(nouucp, `noscpecial') MAILER(local)dnl MAILER(smtp)dnl to sendmail.cf, but all the output I get when running m4 is: VERSIONID($Id: generic-linux.mc,v 8.1 1999/09/24 22:48:05 gshapiro Exp $) OSTYPE(linux)DOMAIN(generic) FEATURE(nouucp, noscpecial) MAILER(local)MAILER(smtp) Am I doing something wrong?

    Read the article

  • Sendmail + m4 - problem converting mc files into cf

    - by zbigh
    Hi I'm currently trying to configure sendmail fo the first time and setup a mail server on a small embedded computer ( running a custom linux distribution ). I'm having an issue with the m4 macros: I'm trying to convert this: VERSIONID(`$Id: generic-linux.mc,v 8.1 1999/09/24 22:48:05 gshapiro Exp $') OSTYPE(linux)dnl DOMAIN(generic)dnl define(HELPFILE, `/etc/mail/helpfile') FEATURE(nouucp, `noscpecial') MAILER(local)dnl MAILER(smtp)dnl to sendmail.cf, but all the output I get when running m4 is: VERSIONID($Id: generic-linux.mc,v 8.1 1999/09/24 22:48:05 gshapiro Exp $) OSTYPE(linux)DOMAIN(generic) FEATURE(nouucp, noscpecial) MAILER(local)MAILER(smtp) Am I doing something wrong?

    Read the article

  • What might cause this ExecutionEngineException?

    - by Qwertie
    I am trying to use Reflection.Emit to generate a wrapper class in a dynamic assembly. Automatic wrapper generation is part of a new open-source library I'm writing called "GoInterfaces". The wrapper class implements IEnumerable<string> and wraps List<string>. In C# terms, all it does is this: class List1_7931B0B4_79328AA0 : IEnumerable<string> { private readonly List<string> _obj; public List1_7931B0B4_79328AA0(List<string> obj) { this._obj = obj; } IEnumerator IEnumerable.GetEnumerator() { return this._obj.GetEnumerator(); } public sealed IEnumerator<string> GetEnumerator() { return this._obj.GetEnumerator(); } } However, when I try to call the GetEnumerator() method on my wrapper class, I get ExecutionEngineException. So I saved my dynamic assembly to a DLL and used ildasm on it. Is there anything wrong with the following code? .class public auto ansi sealed List`1_7931B0B4_79328AA0 extends [mscorlib]System.Object implements [mscorlib]System.Collections.Generic.IEnumerable`1<string>, [Loyc.Runtime]Loyc.Runtime.IGoInterfaceWrapper { .field private initonly class [mscorlib]System.Collections.Generic.List`1<string> _obj .method public hidebysig virtual final instance class [mscorlib]System.Collections.Generic.IEnumerator`1<string> GetEnumerator() cil managed { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Collections.Generic.List`1<string> List`1_7931B0B4_79328AA0::_obj IL_0006: call instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> class [mscorlib]System.Collections.Generic.List`1<string>::GetEnumerator() IL_000b: ret } // end of method List`1_7931B0B4_79328AA0::GetEnumerator .method public hidebysig virtual final instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() cil managed { .override [mscorlib]System.Collections.IEnumerable::GetEnumerator // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Collections.Generic.List`1<string> List`1_7931B0B4_79328AA0::_obj IL_0006: call instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> class [mscorlib]System.Collections.Generic.List`1<string>::GetEnumerator() IL_000b: ret } // end of method List`1_7931B0B4_79328AA0::System.Collections.IEnumerable.GetEnumerator ... I have a test suite that wraps all sorts of different things, including interfaces derived from other interfaces, and multiple interface methods with identical signatures. It's only when I try to wrap IEnumerable<T> that this problem occurs. I'd be happy to send the source code (2 *.cs files, no dependencies) if anyone would like.

    Read the article

  • Can't operator == be applied to generic types in C#?

    - by Hosam Aly
    According to the documentation of the == operator in MSDN, For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. User-defined value types can overload the == operator (see operator). So can user-defined reference types, although by default == behaves as described above for both predefined and user-defined reference types. So why does this code snippet fail to compile? void Compare<T>(T x, T y) { return x == y; } I get the error Operator '==' cannot be applied to operands of type 'T' and 'T'. I wonder why, since as far as I understand the == operator is predefined for all types? Edit: Thanks everybody. I didn't notice at first that the statement was about reference types only. I also thought that bit-by-bit comparison is provided for all value types, which I now know is not correct. But, in case I'm using a reference type, would the the == operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one? Edit 2: Through trial and error, we learned that the == operator will use the predefined reference comparison when using an unrestricted generic type. Actually, the compiler will use the best method it can find for the restricted type argument, but will look no further. For example, the code below will always print true, even when Test.test<B>(new B(), new B()) is called: class A { public static bool operator==(A x, A y) { return true; } } class B : A { public static bool operator==(B x, B y) { return false; } } class Test { void test<T>(T a, T b) where T : A { Console.WriteLine(a == b); } }

    Read the article

  • How can i use complextype class or multi type class is it generic collection?

    - by programmerist
    i need a complex returning type. i have 4 class returning types COMPLEXTYPE must include Company, Muayene, Radyoloji, Satis because i must return data switch case situation how can i do? Maybe i need generic collections How can i do that? public class GenoTipController { public COMPLEXTYPE Generate(DataModelType modeltype) { _Company company = null; _Muayene muayene = null; _Radyoloji radyoloji = null; _Satis satis = null; switch (modeltype) { case DataModelType.Radyoloji: radyoloji = new Radyoloji(); return radyoloji; break; case DataModelType.Satis: satis = new Satis(); return satis; break; case DataModelType.Muayene: muayene = new Muayene(); return muayene; break; case DataModelType.Company: company = new Company(); return company; break; default: break; } } } public class CompanyView { public static List GetPersonel() { GenoTipController controller = new GenoTipController(); _Company company = controller.Generate(DataModelType.Company); return company.GetPersonel(); } } public enum DataModelType { Radyoloji, Satis, Muayene, Company }

    Read the article

  • ASP.NET error on Bitmap.Save "Exception (0x80004005): A generic error occurred in GDI+."

    - by Batu
    Hi, I have a function which first reads an image from disk, resizes it and then saves to another directory. when i use the Bitmap.Save(directory + theimagename) it returns the error as i stated in the question title. i checked the directory is right, and the given image name doesn't exist in that dir. what is weird, is that the same code works great on the local machine. but when i upload it to my shared server. it just doesn't work. the code is below. bmpOut = new Bitmap(Size, Size); Graphics g = Graphics.FromImage(bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle(Brushes.White, 0, 0, Size, Size); int topBottomPadding = 0; int leftRightPadding = 0; if (Size > lnNewWidth + 1) leftRightPadding = Convert.ToInt32((Size - lnNewWidth) / 2); else if (Size > lnNewHeight + 1) topBottomPadding = Convert.ToInt32((Size - lnNewHeight) / 2); g.DrawImage(loBMP, leftRightPadding, topBottomPadding, lnNewWidth, lnNewHeight); Bitmap bmp = new Bitmap(bmpOut); if (bmp != null) bmp.Save(ResizedOutput); bmp.Dispose(); bmpOut.Dispose(); g.Dispose(); loBMP.Dispose(); stack trace: [ExternalException (0x80004005): A generic error occurred in GDI+.] System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +377630 System.Drawing.Image.Save(String filename, ImageFormat format) +69 System.Drawing.Image.Save(String filename) +25 Utilities.ResizeImage(String fileName, String mode) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\App_Code\Utilities.cs:181 Link.ToProductImage(String fileName) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\App_Code\Link.cs:79 Product.PopulateControls(ProductDetails pd) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\Product.aspx.cs:37 Product.Page_Load(Object sender, EventArgs e) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\Product.aspx.cs:20

    Read the article

  • How am I able to create A List<T> containing a generic Interface?

    - by Conrad Clark
    I have a List which must contain IInteract Objects. But IInteract is a generic interface which requires 2 type arguments. My main idea is iterate through a list of Objects and "Interact" one with another if they didn't interact yet. So i have this object List<IObject> WorldObjects = new List<IObject>(); and this one: private List<IInteract> = new List<IInteract>(); Except I can't compile the last line because IInteract requires 2 type arguments. But I don't know what the arguments are until I add them. I could add interactions between Objects of Type A and A... or Objects of Type B and C. I want to create "Interaction" classes which do something with the "acting" object and the "target" object, but I want them to be independent from the objects... so I could add an Interaction between for instance... "SuperUltraClass" and... an "integer". Am I using the wrong approach?

    Read the article

  • Java: how do I get a class literal from a generic type?

    - by Tom
    Typically, I've seen people use the class literal like this: Class<Foo> cls = Foo.class; But what if the type is generic, e.g. List? This works fine, but has a warning since List should be parameterized: Class<List> cls = List.class So why not add a <?>? Well, this causes a type mismatch error: Class<List<?>> cls = List.class I figured something like this would work, but this is just a plain ol' a syntax error: Class<List<Foo>> cls = List<Foo>.class How can I get a Class<List<Foo>> statically, e.g. using the class literal? I could use @SuppressWarnings("unchecked") to get rid of the warnings caused by the non-parameterized use of List in the first example, Class<List> cls = List.class, but I'd rather not. Any suggestions? Thanks!

    Read the article

  • Can't access resource from Generic.xaml within the Custom Control constructor.

    - by myermian
    I'm not sure why this is doing this, but I can't access the resource from within my constructor. XTabItem.cs using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace MyStuff { public class XTabItem : TabItem { public static readonly DependencyProperty XTabItemNormalBackgroundProperty; /// <summary> /// Visual Property: Normal Background /// </summary> [Description("Determines the visibility of the close button."), Category("XTabItem Visual")] public Brush XTabItemNormalBackground { get { return (Brush)GetValue(XTabItemNormalBackgroundProperty); } set { SetValue(XTabItemNormalBackgroundProperty, value); } } static XTabItem() { DefaultStyleKeyProperty.OverrideMetadata(typeof(XTabItem), new FrameworkPropertyMetadata(typeof(XTabItem))); XTabItemNormalBackgroundProperty = DependencyProperty.Register("XTabItemNormalBackground", typeof(Brush), typeof(XTabItem), new UIPropertyMetadata(null)); } public XTabItem() { //XTabItemNormalBackground = (Brush)this.TryFindResource("XTabItemNormalBackgroundBrush"); //THIS DOES NOT WORK?? } public override void OnApplyTemplate() { base.OnApplyTemplate(); } } } Generic.xaml <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:MyStuff" xmlns:con="clr-namespace:MyStuff.Converters" > <SolidColorBrush x:Key="XTabItemNormalBackgroundBrush" Color="BlueViolet" /> <Style TargetType="{x:Type local:XTabItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:XTabItem}"> <!-- CONTENT TEMPLATE --> <Grid SnapsToDevicePixels="True"> <Border x:Name="_Border" Background="{Binding Path=XTabItemNormalBackground, RelativeSource={RelativeSource Mode=TemplatedParent}}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1,1,1,0"> ... </Border> </Grid> </Style> </ResourceDictionary>

    Read the article

  • Is there a generic way of dealing with varying connection strings in C#?

    - by James Wiseman
    I have an application that needs to connect to a SQL database, and execute a SQL Agent Job. The connection string I am trying to access is stored in the registry, which is easily enough pulled out. This appliction is to be run on multiple computers, and I cannot guarantee the format of this connection string being consistent across these computers. Two that I have pulled out for example are: Data Source=Server1;Initial Catalog=DB1;Integrated Security=SSPI; Data Source=Server2;Initial Catalog=DB1;Provider=SQLNCLI.1;Integrated Security=SSPI;Auto Translate=False; I can use an object of type System.Data.SqlClient.SqlConnection to connect to the database with the first connection string, howevever, I get the following error when I pass the second to it: keyword not supported: 'provider' Similarly, I can use the an object of type System.Data.OleDb.OleDbConnection to connect to the database with the second connection string, howevever, I get the following error when I pass the first to it: An OLEDB Provider was not specified in the ConnectionString' I can solve this by scanning the string for 'Provider' and doing the connect conditionally, however I can't help but feel that there is a better way of doing this, and handle the connection strings in a more generic fashion. Does anyone have any suggestions?

    Read the article

< Previous Page | 38 39 40 41 42 43 44 45 46 47 48 49  | Next Page >