Search Results

Search found 18220 results on 729 pages for 'generic programming'.

Page 18/729 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Casting a non-generic type to a generic one

    - by John Sheehan
    I've got this class: class Foo { public string Name { get; set; } } And this class class Foo<T> : Foo { public T Data { get; set; } } Here's what I want to do: public Foo<T> GetSome() { Foo foo = GetFoo(); Foo<T> foot = (Foo<T>)foo; foot.Data = GetData<T>(); return foot; } What's the easiest way to convert Foo to Foo<T>? I can't cast directly InvalidCastException) and I don't want to copy each property manually (in my actual use case, there's more than one property) if I don't have to. Is a user-defined type conversion the way to go?

    Read the article

  • django generic view update/create: update works but create raises IntegrityError

    - by smarber
    I'm using CreateView and UpdateView directely into urls.py of my application whose name is dydict. In the file forms.py I'm using ModelForm and I'm exluding a couple of fields from being shown, some of which sould be set when either creating or updating. So, as mentioned in the title, update part works but create part doesn't which is obvious because required fields that I have exluded are sent empty which is not allowed in my case. So the question here is, how should I do to fill exluded fields into the file forms.py so that I don't have to override CreateView? Thanks in advance.

    Read the article

  • c# inheriting generic collection and serialization...

    - by Stecy
    Hi, The setup: class Item { private int _value; public Item() { _value = 0; } public int Value { get { return _value; } set { _value = value; } } } class ItemCollection : Collection<Item> { private string _name; public ItemCollection() { _name = string.Empty; } public string Name { get {return _name;} set {_name = value;} } } Now, trying to serialize using the following code fragment: ItemCollection items = new ItemCollection(); ... XmlSerializer serializer = new XmlSerializer(typeof(ItemCollection)); using (FileStream f = File.Create(fileName)) serializer.Serialize(f, items); Upon looking at the resulting XML I see that the ItemCollection.Name value is not there! I think what may be happening is that the serializer sees the ItemCollection type as a simple Collection thus ignoring any other added properties... Is there anyone having encountered such a problem and found a solution? Regards, Stécy

    Read the article

  • Explicitly instantiating a generic member function of a generic structure

    - by Dennis Zickefoose
    I have a structure with a template parameter, Stream. Within that structure, there is a function with its own template parameter, Type. If I try to force a specific instance of the function to be generated and called, it works fine, if I am in a context where the exact type of the structure is known. If not, I get a compile error. This feels like a situation where I'm missing a typename, but there are no nested types. I suspect I'm missing something fundamental, but I've been staring at this code for so long all I see are redheads, and frankly writing code that uses templates has never been my forte. The following is the simplest example I could come up with that illustrates the issue. #include <iostream> template<typename Stream> struct Printer { Stream& str; Printer(Stream& str_) : str(str_) { } template<typename Type> Stream& Exec(const Type& t) { return str << t << std::endl; } }; template<typename Stream, typename Type> void Test1(Stream& str, const Type& t) { Printer<Stream> out = Printer<Stream>(str); /****** vvv This is the line the compiler doesn't like vvv ******/ out.Exec<bool>(t); /****** ^^^ That is the line the compiler doesn't like ^^^ ******/ } template<typename Type> void Test2(const Type& t) { Printer<std::ostream> out = Printer<std::ostream>(std::cout); out.Exec<bool>(t); } template<typename Stream, typename Type> void Test3(Stream& str, const Type& t) { Printer<Stream> out = Printer<Stream>(str); out.Exec(t); } int main() { Test2(5); Test3(std::cout, 5); return 0; } As it is written, gcc-4.4 gives the following: test.cpp: In function 'void Test1(Stream&, const Type&)': test.cpp:22: error: expected primary-expression before 'bool' test.cpp:22: error: expected ';' before 'bool' Test2 and Test3 both compile cleanly, and if I comment out Test1 the program executes, and I get "1 5" as I expect. So it looks like there's nothing wrong with the idea of what I want to do, but I've botched something in the implementation. If anybody could shed some light on what I'm overlooking, it would be greatly appreciated.

    Read the article

  • generic identifier

    - by Werner
    Hi, as I probably do not describe the problem in the right terms, I was not able to get an answer with google. Please excuse! In the following code, I would like to replace 'hardcoded' identifier COMMENT with the variable editedField. How to do that? var editedField:String = event.dataField; if (model.multipleProcessingData[i][editedInformationProductNO].COMMENT != null{ ... }

    Read the article

  • Class hierarchy problem (with generic's variance!)

    - by devoured elysium
    The problem: class StatesChain : IState, IHasStateList { private TasksChain tasks = new TasksChain(); ... public IList<IState> States { get { return _taskChain.Tasks; } } IList<ITask> IHasTasksCollection.Tasks { get { return _taskChain.Tasks; } <-- ERROR! You can't do this in C#! I want to return an IList<ITask> from an IList<IStates>. } } Assuming the IList returned will be read-only, I know that what I'm trying to achieve is safe (or is it not?). Is there any way I can accomplish what I'm trying? I wouldn't want to try to implement myself the TasksChain algorithm (again!), as it would be error prone and would lead to code duplication. Maybe I could just define an abstract Chain and then implement both TasksChain and StatesChain from there? Or maybe implementing a Chain<T> class? How would you approach this situation? The Details: I have defined an ITask interface: public interface ITask { bool Run(); ITask FailureTask { get; } } and a IState interface that inherits from ITask: public interface IState : ITask { IState FailureState { get; } } I have also defined an IHasTasksList interface: interface IHasTasksList { List<Tasks> Tasks { get; } } and an IHasStatesList: interface IHasTasksList { List<Tasks> States { get; } } Now, I have defined a TasksChain, that is a class that has some code logic that will manipulate a chain of tasks (beware that TasksChain is itself a kind of ITask!): class TasksChain : ITask, IHasTasksList { IList<ITask> tasks = new List<ITask>(); ... public List<ITask> Tasks { get { return _tasks; } } ... } I am implementing a State the following way: public class State : IState { private readonly TaskChain _taskChain = new TaskChain(); public State(Precondition precondition, Execution execution) { _taskChain.Tasks.Add(precondition); _taskChain.Tasks.Add(execution); } public bool Run() { return _taskChain.Run(); } public IState FailureState { get { return (IState)_taskChain.Tasks[0].FailureTask; } } ITask ITask.FailureTask { get { return FailureState; } } } which, as you can see, makes use of explicit interface implementations to "hide" FailureTask and instead show FailureState property. The problem comes from the fact that I also want to define a StatesChain, that inherits both from IState and IHasStateList (and that also imples ITask and IHasTaskList, implemented as explicit interfaces) and I want it to also hide IHasTaskList's Tasks and only show IHasStateList's States. (What is contained in "The problem" section should really be after this, but I thought puting it first would be way more reader friendly). (pff..long text) Thanks!

    Read the article

  • Generic List created at runtime

    - by Perry
    Hi... i neeed something like this in C#.. have list in class but decide what will be in list during runtime class A { List data; Type typeOfDataInList; } public void FillData(DataTyp[] data) where DataTyp : struct { A a = new A(); A.vListuBudouDataTypu = typeof(DataTyp); A.data = new List(); A.AddRange(data); } Is this possible to do something like this ?

    Read the article

  • C# Calling Methods in Generic Classes

    - by aip.cd.aish
    I am extending the ImageBox control from EmguCV. The control's Image property can be set to anything implementing the IImage interface. All of the following implement this interface: Image<Bgr, Byte> Image<Ycc, Byte> Image<Hsv, Byte> Now I want to call the Draw method on the object of the above type (what ever it may be). The problem is when I access the Image property, the return type is IImage. IImage does not implement the Draw method, but all of the above do. I believe I can cast the object of type IImage to one of the above (the right one) and I can access the Draw method. But how do I know what the right one is? If you have a better way of doing this, please suggest that as well.

    Read the article

  • C# method generic params parameter bug?

    - by Mike M
    Hey, I appears to me as though there is a bug/inconsistency in the C# compiler. This works fine (first method gets called): public void SomeMethod(string message, object data); public void SomeMethod(string message, params object[] data); // .... SomeMethod("woohoo", item); Yet this causes "The call is ambiguous between the following methods" error: public void SomeMethod(string message, T data); public void SomeMethod(string message, params T[] data); // .... SomeMethod("woohoo", (T)item); I could just use the dump the first method entirely, but since this is a very performance sensitive library and the first method will be used about 75% of the time, I would rather not always wrap things in an array and instantiate an iterator to go over a foreach if there is only one item. Splitting into different named methods would be messy at best IMO. Thoughts?

    Read the article

  • c# Generic overloaded method dispatching ambiguous

    - by sebgod
    Hello, I just hit a situation where a method dispatch was ambiguous and wondered if anyone could explain on what basis the compiler (.NET 4.0.30319) chooses what overload to call interface IfaceA { } interface IfaceB<T> { void Add(IfaceA a); T Add(T t); } class ConcreteA : IfaceA { } class abstract BaseClassB<T> : IfaceB<T> { public virtual T Add(T t) { ... } public virtual void Add(IfaceA a) { ... } } class ConcreteB : BaseClassB<IfaceA> { // does not override one of the relevant methods } void code() { var concreteB = new ConcreteB(); // it will call void Add(IfaceA a) concreteB.Add(new ConcreteA()); } In any case, why does the compiler not warn me or even why does it compile? Thank you very much for any answers.

    Read the article

  • Cannot inherit from generic base class and specific interface using same type with generic constrain

    - by simendsjo
    Sorry about the strange title. I really have no idea how to express it any better... I get an error on the following snippet. I use the class Dummy everywhere. Doesn't the compiler understand the constraint I've added on DummyImplBase? Is this a compiler bug as it works if I use Dummy directly instead of setting it as a constraint? Error 1 'ConsoleApplication53.DummyImplBase' does not implement interface member 'ConsoleApplication53.IRequired.RequiredMethod()'. 'ConsoleApplication53.RequiredBase.RequiredMethod()' cannot implement 'ConsoleApplication53.IRequired.RequiredMethod()' because it does not have the matching return type of 'ConsoleApplication53.Dummy'. C:\Documents and Settings\simen\My Documents\Visual Studio 2008\Projects\ConsoleApplication53\ConsoleApplication53\Program.cs 37 27 ConsoleApplication53 public class Dummy { } public interface IRequired<T> { T RequiredMethod(); } public interface IDummyRequired : IRequired<Dummy> { void OtherMethod(); } public class RequiredBase<T> : IRequired<T> { public T RequiredMethod() { return default(T); } } public abstract class DummyImplBase<T> : RequiredBase<T>, IDummyRequired where T: Dummy { public void OtherMethod() { } }

    Read the article

  • Generic TypeIdenitifier convertion.How?

    - by John
    How do I convert the TypeIdenitifier to a class type? I need to use implicit convertion. type TMyChildArray<T>=class(TMyArray<T>) private FData:Array of T; procedure AddEnd(); end; TTypeIdenitifierParentClass=class(TAnotherParentClass) protected TestField:Cardinal; end; procedure TMyChildArray<T>.AddEnd(); var elem:T; begin for elem in Fdata do TTypeIdenitifierParentClass(elem).TestField:=0; end; I get "Invalid typecast" on the implicit convertion "TTypeIdenitifierParentClass(elem).TestField:=0;". The principle I want to use is that the TypeIdenitifier will represent a class that descends from TTypeIdenitifierParentClass.There are many class types,but all of them descend that class. How do I do this?

    Read the article

  • How to call a generic method through reflection

    - by milan
    Hi, is it possible to call with reflection a method with "explict type argument" <S> definition e.g. oObject.Cast<S>() ? where is: IList <P> oObject = new List <P>(); I tried with oObject.getType().InvokeMember( "Cast", BindingFlags.InvokeMethod, null, oObject, null) but it does not work, does anyone know why?

    Read the article

  • how to create property of type generic class?

    - by Anish
    public class SelectionList<T> : ObservableCollection<SelectionItem<T>> where T : IComparable<T> { // Code } public class SelectionItem<T> : INotifyPropertyChanged { // Code } I need to create a property which is of the type SelectionList...as follows: public SelectionList<string> Sports { get; set; }. But when I replace string with DataRowView, as public SelectionList<DataRowView> Sports { get; set; }. I am getting error. Please help

    Read the article

  • Can't install or update Ubuntu after using parameter acpi_osi = Linux

    - by Lucas Leitão
    I recently had an issue with my acer 4736z notebook because I was having a blank screen after booting the OS, then someone told me to use the parameter GRUB_CMDLINE_LINUX_DEFAULT = "quiet splash acpi_osi = Linux" after quiet splash inside the grub. It worked for me, but since then I can't install a thing or update anything on Linux because it says Removing linux-image-extra-3.5.0-17-generic ... Examining /etc/kernel/postrm.d . run-parts: executing /etc/kernel/postrm.d/initramfs-tools 3.5.0-17-generic /boot/vmlinuz-3.5.0-17-generic update-initramfs: Deleting /boot/initrd.img-3.5.0-17-generic run-parts: executing /etc/kernel/postrm.d/zz-update-grub 3.5.0-17-generic /boot/vmlinuz-3.5.0-17-generic /usr/sbin/grub-mkconfig: 11: /etc/default/grub: GRUB_CMDLINE_LINUX_DEFAULT: not found run-parts: /etc/kernel/postrm.d/zz-update-grub exited with return code 127 Failed to process /etc/kernel/postrm.d at /var/lib/dpkg/info/linux-image-extra-3.5.0-17-generic.postrm line 328. dpkg: erro ao processar linux-image-extra-3.5.0-17-generic (--remove): sub-processo script post-removal instalado retornou estado de saída de erro 1 Removendo linux-image-3.5.0-17-generic ... Examining /etc/kernel/postrm.d . run-parts: executing /etc/kernel/postrm.d/initramfs-tools 3.5.0-17-generic /boot/vmlinuz-3.5.0-17-generic update-initramfs: Deleting /boot/initrd.img-3.5.0-17-generic run-parts: executing /etc/kernel/postrm.d/zz-update-grub 3.5.0-17-generic /boot/vmlinuz-3.5.0-17-generic /usr/sbin/grub-mkconfig: 11: /etc/default/grub: GRUB_CMDLINE_LINUX_DEFAULT: not found run-parts: /etc/kernel/postrm.d/zz-update-grub exited with return code 127 Failed to process /etc/kernel/postrm.d at /var/lib/dpkg/info/linux-image-3.5.0-17-generic.postrm line 328. dpkg: erro ao processar linux-image-3.5.0-17-generic (--remove): sub-processo script post-removal instalado retornou estado de saída de erro 1 Erros foram encontrados durante o processamento de: linux-image-extra-3.5.0-17-generic linux-image-3.5.0-17-generic E: Sub-process /usr/bin/dpkg returned an error code (1) I already tried to remove older kernels but it gives me the same message. Do you have a clue about what should I do?

    Read the article

  • What to do when the programming activity becomes a problem?

    - by gablin
    I once saw a program (can't remember which) where it talked about people "experiencing flow" when they are doing something they are passionate about. When "in flow", they tend to lose track of time and surrounding, concentrating only on their activity at hand. This happens a lot for me when I program; most particularly when I face a problem. I refuse to give up until it's solved. This usually leads to hours just rushing by and I forget to eat lunch, dinner gets pushed into far into the evening, and when I finally look at the clock, it's way into the wee-hours of the night and I will only get a few hours of sleep before having to rise early in the morning. (This is not to say that I'm in flow only when facing a problem - but I find it particularly hard to stop programming and step back when there's something I can't solve immediately.) I love programming, but I hate it when it disrupts my normal routines (most importantly eating and sleeping patterns). And sitting still for so many hours, staring a screen, is not healthy. Please, any ideas on how I can get my rampant programming activity under control?

    Read the article

  • Which programming language should i choose? (much more info inside) [closed]

    - by Andreas
    I am not completely sure if this is the right place to put this question, but since it's the programming thread I guessed that there's many experienced programmers here. :) Ok, hello! My name is Andreas and I am a 16 years old guy from Norway. For some time now I've wanted to learn a programming language. Six months ago I started learning C++, but quit withing a week due to lack of motivation. The same thing happend only 2 months ago when I tried to learn Lua. I wanted to program mods to the game Garry's mod, and was really motivated. Then I stopped playing the game, and the programming stopped with it. Today though I am ready again. The only difference is that I am not completely sure what I want to do with the language. I only want to create something, and I miss the progress of failing and enduring hard work until I finally solve the problem I've worked on for hours. What I am trying to say is; Is there any program out there that allows me, a complete noob (I didn't learn that much in a week, so I like to call myself a beginner), to create apps, mods or something similar but at the same time being qualified as a first time language? I was thinking of Java, because Android, Minecraft and many other applications and games use it. But I've heard that it is going to be replaced by a program called HTML 5 (whatever that is), is this true? I certainly don't want to spend many hours of my life on something that is useless in a year or two. Hopefully I didn't make this too complicated. I know that it is hard to recommend something when I don't have a goal, but I really don't know what to say. Have a good day kind folks! - Andreas EDIT:* I did not know that this was an off topic question, really sorry!

    Read the article

  • Is there any place to find real-world usage-style tutorials for programming languages?

    - by OleDid
    Let's face it. When you want to learn something completely new, be it mathematics or foreign languages, it's easiest to learn when you get real world scenarios in front of you, with theory applied. For example, trigonometry can be extremely interesting when applied to creation of 2D platform games. Norwegian can be really interesting to learn if you live in Norway. When I try to look at a new programming language, I always find these steps the hardest: What tools do I need to compile and how do I do it Introduction-step: Why is this programming language so cool? Where and how is it used? (The step I am looking for, real-world scenarios) The rest, deep diving into the language, pure theory and such, is often much easier if you have completed step 1 and 2. Because now you know what it's all about, and can just read the specification when you need to. What I ask is, do you have any recommendations for places I can find such material for programming languages? Be it websites or companies selling books in this style, I'm interested. Also, I am interested in all languages. (If I had found a "real-world usage" explained for even INTERCAL, I would be interested). In some other thread here, I found a book called "Seven Languages in Seven Weeks". This is kind of what I am looking for, but I believe there must be "more like this".

    Read the article

  • C#/.NET Little Wonders: The Predicate, Comparison, and Converter Generic Delegates

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. In the last three weeks, we examined the Action family of delegates (and delegates in general), the Func family of delegates, and the EventHandler family of delegates and how they can be used to support generic, reusable algorithms and classes. This week I will be completing my series on the generic delegates in the .NET Framework with a discussion of three more, somewhat less used, generic delegates: Predicate<T>, Comparison<T>, and Converter<TInput, TOutput>. These are older generic delegates that were introduced in .NET 2.0, mostly for use in the Array and List<T> classes.  Though older, it’s good to have an understanding of them and their intended purpose.  In addition, you can feel free to use them yourself, though obviously you can also use the equivalents from the Func family of delegates instead. Predicate<T> – delegate for determining matches The Predicate<T> delegate was a very early delegate developed in the .NET 2.0 Framework to determine if an item was a match for some condition in a List<T> or T[].  The methods that tend to use the Predicate<T> include: Find(), FindAll(), FindLast() Uses the Predicate<T> delegate to finds items, in a list/array of type T, that matches the given predicate. FindIndex(), FindLastIndex() Uses the Predicate<T> delegate to find the index of an item, of in a list/array of type T, that matches the given predicate. The signature of the Predicate<T> delegate (ignoring variance for the moment) is: 1: public delegate bool Predicate<T>(T obj); So, this is a delegate type that supports any method taking an item of type T and returning bool.  In addition, there is a semantic understanding that this predicate is supposed to be examining the item supplied to see if it matches a given criteria. 1: // finds first even number (2) 2: var firstEven = Array.Find(numbers, n => (n % 2) == 0); 3:  4: // finds all odd numbers (1, 3, 5, 7, 9) 5: var allEvens = Array.FindAll(numbers, n => (n % 2) == 1); 6:  7: // find index of first multiple of 5 (4) 8: var firstFiveMultiplePos = Array.FindIndex(numbers, n => (n % 5) == 0); This delegate has typically been succeeded in LINQ by the more general Func family, so that Predicate<T> and Func<T, bool> are logically identical.  Strictly speaking, though, they are different types, so a delegate reference of type Predicate<T> cannot be directly assigned to a delegate reference of type Func<T, bool>, though the same method can be assigned to both. 1: // SUCCESS: the same lambda can be assigned to either 2: Predicate<DateTime> isSameDayPred = dt => dt.Date == DateTime.Today; 3: Func<DateTime, bool> isSameDayFunc = dt => dt.Date == DateTime.Today; 4:  5: // ERROR: once they are assigned to a delegate type, they are strongly 6: // typed and cannot be directly assigned to other delegate types. 7: isSameDayPred = isSameDayFunc; When you assign a method to a delegate, all that is required is that the signature matches.  This is why the same method can be assigned to either delegate type since their signatures are the same.  However, once the method has been assigned to a delegate type, it is now a strongly-typed reference to that delegate type, and it cannot be assigned to a different delegate type (beyond the bounds of variance depending on Framework version, of course). Comparison<T> – delegate for determining order Just as the Predicate<T> generic delegate was birthed to give Array and List<T> the ability to perform type-safe matching, the Comparison<T> was birthed to give them the ability to perform type-safe ordering. The Comparison<T> is used in Array and List<T> for: Sort() A form of the Sort() method that takes a comparison delegate; this is an alternate way to custom sort a list/array from having to define custom IComparer<T> classes. The signature for the Comparison<T> delegate looks like (without variance): 1: public delegate int Comparison<T>(T lhs, T rhs); The goal of this delegate is to compare the left-hand-side to the right-hand-side and return a negative number if the lhs < rhs, zero if they are equal, and a positive number if the lhs > rhs.  Generally speaking, null is considered to be the smallest value of any reference type, so null should always be less than non-null, and two null values should be considered equal. In most sort/ordering methods, you must specify an IComparer<T> if you want to do custom sorting/ordering.  The Array and List<T> types, however, also allow for an alternative Comparison<T> delegate to be used instead, essentially, this lets you perform the custom sort without having to have the custom IComparer<T> class defined. It should be noted, however, that the LINQ OrderBy(), and ThenBy() family of methods do not support the Comparison<T> delegate (though one could easily add their own extension methods to create one, or create an IComparer() factory class that generates one from a Comparison<T>). So, given this delegate, we could use it to perform easy sorts on an Array or List<T> based on custom fields.  Say for example we have a data class called Employee with some basic employee information: 1: public sealed class Employee 2: { 3: public string Name { get; set; } 4: public int Id { get; set; } 5: public double Salary { get; set; } 6: } And say we had a List<Employee> that contained data, such as: 1: var employees = new List<Employee> 2: { 3: new Employee { Name = "John Smith", Id = 2, Salary = 37000.0 }, 4: new Employee { Name = "Jane Doe", Id = 1, Salary = 57000.0 }, 5: new Employee { Name = "John Doe", Id = 5, Salary = 60000.0 }, 6: new Employee { Name = "Jane Smith", Id = 3, Salary = 59000.0 } 7: }; Now, using the Comparison<T> delegate form of Sort() on the List<Employee>, we can sort our list many ways: 1: // sort based on employee ID 2: employees.Sort((lhs, rhs) => Comparer<int>.Default.Compare(lhs.Id, rhs.Id)); 3:  4: // sort based on employee name 5: employees.Sort((lhs, rhs) => string.Compare(lhs.Name, rhs.Name)); 6:  7: // sort based on salary, descending (note switched lhs/rhs order for descending) 8: employees.Sort((lhs, rhs) => Comparer<double>.Default.Compare(rhs.Salary, lhs.Salary)); So again, you could use this older delegate, which has a lot of logical meaning to it’s name, or use a generic delegate such as Func<T, T, int> to implement the same sort of behavior.  All this said, one of the reasons, in my opinion, that Comparison<T> isn’t used too often is that it tends to need complex lambdas, and the LINQ ability to order based on projections is much easier to use, though the Array and List<T> sorts tend to be more efficient if you want to perform in-place ordering. Converter<TInput, TOutput> – delegate to convert elements The Converter<TInput, TOutput> delegate is used by the Array and List<T> delegate to specify how to convert elements from an array/list of one type (TInput) to another type (TOutput).  It is used in an array/list for: ConvertAll() Converts all elements from a List<TInput> / TInput[] to a new List<TOutput> / TOutput[]. The delegate signature for Converter<TInput, TOutput> is very straightforward (ignoring variance): 1: public delegate TOutput Converter<TInput, TOutput>(TInput input); So, this delegate’s job is to taken an input item (of type TInput) and convert it to a return result (of type TOutput).  Again, this is logically equivalent to a newer Func delegate with a signature of Func<TInput, TOutput>.  In fact, the latter is how the LINQ conversion methods are defined. So, we could use the ConvertAll() syntax to convert a List<T> or T[] to different types, such as: 1: // get a list of just employee IDs 2: var empIds = employees.ConvertAll(emp => emp.Id); 3:  4: // get a list of all emp salaries, as int instead of double: 5: var empSalaries = employees.ConvertAll(emp => (int)emp.Salary); Note that the expressions above are logically equivalent to using LINQ’s Select() method, which gives you a lot more power: 1: // get a list of just employee IDs 2: var empIds = employees.Select(emp => emp.Id).ToList(); 3:  4: // get a list of all emp salaries, as int instead of double: 5: var empSalaries = employees.Select(emp => (int)emp.Salary).ToList(); The only difference with using LINQ is that many of the methods (including Select()) are deferred execution, which means that often times they will not perform the conversion for an item until it is requested.  This has both pros and cons in that you gain the benefit of not performing work until it is actually needed, but on the flip side if you want the results now, there is overhead in the behind-the-scenes work that support deferred execution (it’s supported by the yield return / yield break keywords in C# which define iterators that maintain current state information). In general, the new LINQ syntax is preferred, but the older Array and List<T> ConvertAll() methods are still around, as is the Converter<TInput, TOutput> delegate. Sidebar: Variance support update in .NET 4.0 Just like our descriptions of Func and Action, these three early generic delegates also support more variance in assignment as of .NET 4.0.  Their new signatures are: 1: // comparison is contravariant on type being compared 2: public delegate int Comparison<in T>(T lhs, T rhs); 3:  4: // converter is contravariant on input and covariant on output 5: public delegate TOutput Contravariant<in TInput, out TOutput>(TInput input); 6:  7: // predicate is contravariant on input 8: public delegate bool Predicate<in T>(T obj); Thus these delegates can now be assigned to delegates allowing for contravariance (going to a more derived type) or covariance (going to a less derived type) based on whether the parameters are input or output, respectively. Summary Today, we wrapped up our generic delegates discussion by looking at three lesser-used delegates: Predicate<T>, Comparison<T>, and Converter<TInput, TOutput>.  All three of these tend to be replaced by their more generic Func equivalents in LINQ, but that doesn’t mean you shouldn’t understand what they do or can’t use them for your own code, as they do contain semantic meanings in their names that sometimes get lost in the more generic Func name.   Tweet Technorati Tags: C#,CSharp,.NET,Little Wonders,delegates,generics,Predicate,Converter,Comparison

    Read the article

  • viable part-time career in IT/programming?

    - by Rider
    Hi, I'd like to ask for some career advice from you people. Is there a viable job/career that can be done in programming/IT for the long term? Right now, I am thinking about website (PHP?) developer path. My background: I have a degree in computer science and have been a programmer/system analyst for almost 10 years. Lately I took a big break from programming and studied for a B.arch. degree (yes architecture), only to discover that architecture offers zero (0) jobs where I'm from, for 3 years already (and no, I am not going to move and the grass in not greener in other places). I have never been particularly interested in programming, in fact I was bored by it. But I was always quite good at both programming and system analysis, and very valued by practically all my employers. On the other hand, I have never been valued or offered a good job in any other field (although I can do many things, like design, architecture, translations, documentation, teaching, etc etc.) I guess the human component has been always more important for me in programming jobs - I value all the good people I worked with, but not projects. However, I have about zero skills or desire to be a project manager. I also have close to zero skills for selling myself. I like it best when I can do "my thing", have my niche, have an ownership of some project. Right now my career perspective is to do part time programming and to part time teach yoga. I have already started the yoga teaching part. Do you think that part time programming is viable? And what niche works best for that? I have considered web development, QA, or software development in a company like I did before. However, my fear is that when you do programming part-time, you get the most boring coding work, only to see your colleagues move to more interesting projects and up their respective career ladders. I also fear that part-timers are not especially needed either. And, since I don't share much enthusiasm at programming, I'd rather not be around young programmers boiling with geeky enthusiasm about coding, but rather QA mindset with people from different backgrounds and life paths might work better for me. Thanks for any advice, --Rider

    Read the article

  • Errors with linux-image-3.8.0-36-generic and GRUB

    - by user285239
    OS: Ubuntu 12.04 LTS Problem 1: When installing anything (or updating) it always ends with this error: Errors were encountered while processing: linux-image-3.8.0-36-generic linux-image-3.8.0-38-generic linux-image-generic-lts-raring linux-generic-lts-raring Problem 2: When installing or updating stuff it opens some grub files and halts execution until I close these grub files. See screenshot below. Grub files + terminal window (screenshot) Pastebin with terminal output while trying to install something I should mention that I don't known if these two errors are related, but it is a fact that every time I try to install something or run an update both of the above errors pop up. I couldn't find anything of interest in the logs I looked at (probably because I don't know what/where to look), but tell me if you need me to upload something. Edit 02 june. This is the output from lsb_release -a kasper@ubuntuRW:~$ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 12.04.4 LTS Release: 12.04 Codename: precise

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >