Search Results

Search found 3493 results on 140 pages for 'constructor'.

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

  • Entity Framework .. partial constructor

    - by adamjellyit
    Hi .. I intend to extend the constructors of some of the entities in my Entity Framework (4). However how do I ensure that my constructor is run after the model has run its. i.e. I want to ensure that the the object holds the data from the database before I work on it in my constructor.

    Read the article

  • Constructor and Destructor of a singleton object called twice

    - by Bikram990
    I'm facing a problem in singleton object in c++. Here is the explanation: Problem info: I have a 4 shared libraries (say libA.so, libB.so, libC.so, libD.so) and 2 executable binary files each using one another shared library( say libE.so) which deals with files. The purpose of libE.so is to write data into a file and if the executable restarts or size of file exceeds a certain limit it is zipped and a new file is created with time stamp in name. It is using singleton object. It exports a handler class for getting and using singleton. Compressing only happens in the above said two cases. The user/loader executable can specify the starting name of file only no other control is provided by handler class. libA.so, libB.so, libC.so and libD.so have almost same behavior. They all have a class and declare and object of an handler which gets the instance of the singleton in libE.so and uses it for further purpose. All these libraries are linked to two executable binary files. If only one of the two executable runs then its fine, But if both executable runs one after other then the file of the first started executable gets compressed. Debug info: The constructor and destructor of the singleton object is called twice.(for each executable) The object of singleton is a static object and never deleted. The executable is not able to exit/return gives: glibc detected * (exe1 or exe2): double free or corruption (!prev): some_addr * Running with binaries valgrind gives that the above error is due to the destructor of the singleton object. Thanks

    Read the article

  • If I define a property to prototype appears in the constructor of object, why?

    - by Eduard Florinescu
    I took the example from this question modified a bit: What is the point of the prototype method? function employee(name,jobtitle,born) { this.name=name; this.jobtitle=jobtitle; this.born=born; this.status="single" } employee.prototype.salary=10000000; var fred=new employee("Fred Flintstone","Caveman",1970); console.log(fred.salary); fred.salary=20000; console.log(fred.salary) And the output in console is this: What is the difference salary is in constructor but I still can access it with fred.salary, how can I see if is in constructor from code, status is still employee property how can I tell for example if name is the one of employee or has been touch by initialization? Why is salary in constructor, when name,jobtitle,born where "touched" by employee("Fred Flintstone","Caveman",1970); «constructor»?

    Read the article

  • Passing List of Strings or Array of strings into Unity Injection Constructor (Config-Based)

    - by miguel
    I cannot seem to get unity working when attempting to pass in an array of strings into a constructor parameter list, while using XML configuration. When I try the following: <typeConfig ...> <constructor ...> <param ... parameterType="System.String[]"> <array> <value.../> <value.../> </array> </param> </constructor> </typeConfig> for a c'tor which looks like this: void Foo(string[] inputParams_){ ... } It always fails in Unity's FindConstructor(...) method stating that it cannot find a c'tor mathcing the parameter type of String.String Does anyone know how to pass an array of stings successfully into this type of c'tor? If not, how can I do so with a list of strings, if the c'tor were to accept an IList? Thanks!

    Read the article

  • Enum "does not have a no-arg default constructor" with Jaxb and cxf

    - by Dave
    A client is having an issue running java2ws on some of their code, which uses & extends classes that are consumed from my SOAP web services. Confused yet? :) I'm exposing a SOAP web service (JBoss5, Java 6). Someone is consuming that web service with Axis1 and creating a jar out of it with the data types and client stubs. They are then defining their own type, which extends one of my types. My type contains an enumeration. class MyParent { private MyEnumType myEnum; // getters, settters for myEnum; } class TheirChild extends MyParent { ... } When they are running java2ws on their code (which extends my class), they get Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions net.foo.bar.MyEnuMType does not have a no-arg default constructor. this problem is related to the following location: at net.foo.bar.MyEnumType at public net.foo.bar.MyEnumType net.foo.bar.MyParent.getMyEnum() The enum I've defined is below. This is now how it comes out after being consumed, but it's how I have it defined on the app server: @XmlType(name = "MyEnumType") @XmlEnum public enum MyEnumType { Val1("Val1"), Val2("Val2") private final String value; MyEnumType(String v) { value = v; } public String value() { return value; } public static MyEnumType fromValue(String v) { if (v == null || v.length() == 0) { return null; } if (v.equals("Val1")) { return MyEnumType.Val1; } if (v.equals("Val2")) { return MyEnumType.Val2; } return null; } } I've seen things online and other posts, like (this one) regarding Jaxb's inability to handle Lists or things like that, but I'm baffled about my enum. I'm pretty sure you can't have a default constructor for an enum (well, at least a public no-arg constructor, Java yells at me when I try), so I'm not sure what makes this error possible. Any ideas? Also, the "2 counts of IllegalAnnotationsExceptions" may be because my code actually has two enums that are written similarly, but I left them out of this example for brevity.

    Read the article

  • Generic object to object mapping with parametrized constructor

    - by Rody van Sambeek
    I have a data access layer which returns an IDataRecord. I have a WCF service that serves DataContracts (dto's). These DataContracts are initiated by a parametrized constructor containing the IDataRecord as follows: [DataContract] public class DataContractItem { [DataMember] public int ID; [DataMember] public string Title; public DataContractItem(IDataRecord record) { this.ID = Convert.ToInt32(record["ID"]); this.Title = record["title"].ToString(); } } Unfortanately I can't change the DAL, so I'm obliged to work with the IDataRecord as input. But in generat this works very well. The mappings are pretty simple most of the time, sometimes they are a bit more complex, but no rocket science. However, now I'd like to be able to use generics to instantiate the different DataContracts to simplify the WCF service methods. I want to be able to do something like: public T DoSomething<T>(IDataRecord record) { ... return new T(record); } So I'd tried to following solutions: Use a generic typed interface with a constructor. doesn't work: ofcourse we can't define a constructor in an interface Use a static method to instantiate the DataContract and create a typed interface containing this static method. doesn't work: ofcourse we can't define a static method in an interface Use a generic typed interface containing the new() constraint doesn't work: new() constraint cannot contain a parameter (the IDataRecord) Using a factory object to perform the mapping based on the DataContract Type. does work, but: not very clean, because I now have a switch statement with all mappings in one file. I can't find a real clean solution for this. Can somebody shed a light on this for me? The project is too small for any complex mapping techniques and too large for a "switch-based" factory implementation.

    Read the article

  • How to handle 'this' pointer in constructor?

    - by Kyle
    I have objects which create other child objects within their constructors, passing 'this' so the child can save a pointer back to its parent. I use boost::shared_ptr extensively in my programming as a safer alternative to std::auto_ptr or raw pointers. So the child would have code such as shared_ptr<Parent>, and boost provides the shared_from_this() method which the parent can give to the child. My problem is that shared_from_this() cannot be used in a constructor, which isn't really a crime because 'this' should not be used in a constructor anyways unless you know what you're doing and don't mind the limitations. Google's C++ Style Guide states that constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method. This solves the 'this-in-constructor' problem as well as a few others as well. What bothers me is that people using your code now must remember to call Init() every time they construct one of your objects. The only way I can think of to enforce this is by having an assertion that Init() has already been called at the top of every member function, but this is tedious to write and cumbersome to execute. Are there any idioms out there that solve this problem at any step along the way?

    Read the article

  • Constructor on type: "Namespace.type" not found.

    - by Nick
    Hello, I am using Castle.Windsor as an IOC. So I am trying to resolve a service type in the constructor of an HTTPHandler. I keep receiving this error, "Constructor on type: "Namespace.type" not found." My configuration has the following entries for service type: IDocumentDirectory <component id="restricted.content.directory" service="org.healthwise.foundations.services.content.IDocumentDirectory, org.healthwise.foundations.services" type="org.healthwise.foundations.services.content.RestrictedLocalizationDocumentDirectory, org.healthwise.foundations.services"> <parameters> <contentDirectory>${content.directory}</contentDirectory> <localizations> <array> <item>en-us</item> <item>es-us</item> </array> </localizations> </parameters> </component> <component id="content.directory" service="org.healthwise.foundations.services.content.IDocumentDirectory, org.healthwise.foundations.services" type="org.healthwise.foundations.services.web.client.WebServiceDocumentDirectory, org.healthwise.foundations.services.web.client"> <parameters> <webServiceURL>#{contentDirectoryWebsiteUrl}</webServiceURL> </parameters> </component> In my new handler the constructor looks like this: public HeartBeatHttpHandler(IDocumentDirectory contentDirectory) { _contentDirectory = contentDirectory; } I have never recieved this error using Castle.Windsor. Can someone explain? Thanks!

    Read the article

  • Problem inserting Pygames on a wxPython panel using Boa Constructor

    - by Kohwalter
    Hello, im new in Python so im hoping to to get some help to figure out what is going wrong. Im trying to run a Pygames from within wxPython panel (made on Boa Constructor). To do that i followed the instructions on the http://wiki.wxpython.org/IntegratingPyGame but still it isn't working. Here is the Panel code that was used to make the integration: class PG_panel(wx.Panel): def __init__(self, ID, name, parent, mypos, mysize): # pygame is imported in this class # make it globally available global pygame #self.Fit() wx.Panel.__init__(self, id=wxID_FRMMAINPANELTABULEIRO, name='panelTabuleiro', parent=self, pos=(16, 96), size=mysize) # pygame uses SDL, set the environment variables os.environ['SDL_WINDOWID'] = str(self.GetHandle()) os.environ['SDL_VIDEODRIVER'] = 'windib' # do the pygame stuff after setting the environment variables import pygame pygame.display.init() # create the pygame window/screen screen = pygame.display.set_mode(464, 464) #(424,450) # start the thread instance self.thread = PG_thread(screen) self.thread.start() def __del__(self): self.thread.stop() And im trying to use that panel on an interface from Boa Constructor, here is the code: class frmMain(wx.Frame): def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRMMAIN, name='frmMain', parent=prnt, pos=wx.Point(660, 239), size=wx.Size(815, 661), style=wx.DEFAULT_FRAME_STYLE, title='Grupo 1 - Jogo de Damas') self._init_utils() self.SetClientSize(wx.Size(799, 623)) self.SetBackgroundColour(wx.Colour(225, 225, 225)) self.SetMinSize(wx.Size(784, 650)) self.Center(wx.BOTH) self.SetMenuBar(self.menuBar1) #here begins my code mysize = (464, 464) mypos = (16, 96) self.panelTabuleiro = PG_panel(wxID_FRMMAINPANELTABULEIRO, 'panelTabuleiro', self, mypos, mysize) The original that was auto-made by the Boa Constructor is the following: self.panelTabuleiro = wx.Panel(id=wxID_FRMMAINPANELTABULEIRO, name='panelTabuleiro', parent=self, pos=wx.Point(16, 96), size=wx.Size(464, 464), style=wx.TAB_TRAVERSAL) self.panelTabuleiro.SetBackgroundColour(wx.Colour(232, 249, 240)) self.panelTabuleiro.SetThemeEnabled(True) self.panelTabuleiro.SetHelpText('Tabuleiro') The error that it gives is: Type error: in method 'new_Panel', expected argument 1 of type 'wxWindow*1 Exception AttributeError: "'PG_panel' object has no attribute 'thread' in ignored Any thoughts ? I appreciate any help. Thank you.

    Read the article

  • Constructor issue

    - by laura
    This is the code that I worked on and I don't understand what it's happening on constructor Package obj2(); On output are displayed only the values 4 (Package obj1(4)) and 2 (Package obj3(2)) #include <iostream> using namespace std; class Package { private: int value; public: Package() { cout<<"constructor #1"<<endl; value = 7; cout << value << endl; } Package(int v) { cout<<"constructor #2"<<endl; value = v; cout << value << endl; } ~Package() { cout<<"destructor"<<endl; cout << value << endl; } }; int main() { Package obj1(4); Package obj2(); Package obj3(2); }

    Read the article

  • How do I use constructor dependency injection to supply Models from a collection to their ViewModels

    - by GraemeF
    I'm using constructor dependency injection in my WPF application and I keep running into the following pattern, so would like to get other people's opinion on it and hear about alternative solutions. The goal is to wire up a hierarchy of ViewModels to a similar hierarchy of Models, so that the responsibility for presenting the information in each model lies with its own ViewModel implementation. (The pattern also crops up under other circumstances but MVVM should make for a good example.) Here's a simplified example. Given that I have a model that has a collection of further models: public interface IPerson { IEnumerable<IAddress> Addresses { get; } } public interface IAddress { } I would like to mirror this hierarchy in the ViewModels so that I can bind a ListBox (or whatever) to a collection in the Person ViewModel: public interface IPersonViewModel { ObservableCollection<IAddressViewModel> Addresses { get; } void Initialize(); } public interface IAddressViewModel { } The child ViewModel needs to present the information from the child Model, so it's injected via the constructor: public class AddressViewModel : IAddressViewModel { private readonly IAddress _address; public AddressViewModel(IAddress address) { _address = address; } } The question is, what is the best way to supply the child Model to the corresponding child ViewModel? The example is trivial, but in a typical real case the ViewModels have more dependencies - each of which has its own dependencies (and so on). I'm using Unity 1.2 (although I think the question is relevant across the other IoC containers), and I am using Caliburn's view strategies to automatically find and wire up the appropriate View to a ViewModel. Here is my current solution: The parent ViewModel needs to create a child ViewModel for each child Model, so it has a factory method added to its constructor which it uses during initialization: public class PersonViewModel : IPersonViewModel { private readonly Func<IAddress, IAddressViewModel> _addressViewModelFactory; private readonly IPerson _person; public PersonViewModel(IPerson person, Func<IAddress, IAddressViewModel> addressViewModelFactory) { _addressViewModelFactory = addressViewModelFactory; _person = person; Addresses = new ObservableCollection<IAddressViewModel>(); } public ObservableCollection<IAddressViewModel> Addresses { get; private set; } public void Initialize() { foreach (IAddress address in _person.Addresses) Addresses.Add(_addressViewModelFactory(address)); } } A factory method that satisfies the Func<IAddress, IAddressViewModel> interface is registered with the main UnityContainer. The factory method uses a child container to register the IAddress dependency that is required by the ViewModel and then resolves the child ViewModel: public class Factory { private readonly IUnityContainer _container; public Factory(IUnityContainer container) { _container = container; } public void RegisterStuff() { _container.RegisterInstance<Func<IAddress, IAddressViewModel>>(CreateAddressViewModel); } private IAddressViewModel CreateAddressViewModel(IAddress model) { IUnityContainer childContainer = _container.CreateChildContainer(); childContainer.RegisterInstance(model); return childContainer.Resolve<IAddressViewModel>(); } } Now, when the PersonViewModel is initialized, it loops through each Address in the Model and calls CreateAddressViewModel() (which was injected via the Func<IAddress, IAddressViewModel> argument). CreateAddressViewModel() creates a temporary child container and registers the IAddress model so that when it resolves the IAddressViewModel from the child container the AddressViewModel gets the correct instance injected via its constructor. This seems to be a good solution to me as the dependencies of the ViewModels are very clear and they are easily testable and unaware of the IoC container. On the other hand, performance is OK but not great as a lot of temporary child containers can be created. Also I end up with a lot of very similar factory methods. Is this the best way to inject the child Models into the child ViewModels with Unity? Is there a better (or faster) way to do it in other IoC containers, e.g. Autofac? How would this problem be tackled with MEF, given that it is not a traditional IoC container but is still used to compose objects?

    Read the article

  • Ninject WithConstructorArgument : No matching bindings are available, and the type is not self-bindable

    - by Jean-François Beauchamp
    My understanding of WithConstructorArgument is probably erroneous, because the following is not working: I have a service, lets call it MyService, whose constructor is taking multiple objects, and a string parameter called testEmail. For this string parameter, I added the following Ninject binding: string testEmail = "[email protected]"; kernel.Bind<IMyService>().To<MyService>().WithConstructorArgument("testEmail", testEmail); However, when executing the following line of code, I get an exception: var myService = kernel.Get<MyService>(); Here is the exception I get: Error activating string No matching bindings are available, and the type is not self-bindable. Activation path: 2) Injection of dependency string into parameter testEmail of constructor of type MyService 1) Request for MyService Suggestions: 1) Ensure that you have defined a binding for string. 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel. 3) Ensure you have not accidentally created more than one kernel. 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name. 5) If you are using automatic module loading, ensure the search path and filters are correct. What am I doing wrong here? UPDATE: Here is the MyService constructor: [Ninject.Inject] public MyService(IMyRepository myRepository, IMyEventService myEventService, IUnitOfWork unitOfWork, ILoggingService log, IEmailService emailService, IConfigurationManager config, HttpContextBase httpContext, string testEmail) { this.myRepository = myRepository; this.myEventService = myEventService; this.unitOfWork = unitOfWork; this.log = log; this.emailService = emailService; this.config = config; this.httpContext = httpContext; this.testEmail = testEmail; } I have standard bindings for all the constructor parameter types. Only 'string' has no binding, and HttpContextBase has a binding that is a bit different: kernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(new HttpContext(new MyHttpRequest("", "", "", null, new StringWriter())))); and MyHttpRequest is defined as follows: public class MyHttpRequest : SimpleWorkerRequest { public string UserHostAddress; public string RawUrl; public MyHttpRequest(string appVirtualDir, string appPhysicalDir, string page, string query, TextWriter output) : base(appVirtualDir, appPhysicalDir, page, query, output) { this.UserHostAddress = "127.0.0.1"; this.RawUrl = null; } }

    Read the article

  • Best Practice With JFrame Constructors?

    - by David Barry
    In both my Java classes, and the books we used in them laying out a GUI with code heavily involved the constructor of the JFrame. The standard technique in the books seems to be to initialize all components and add them to the JFrame in the constructor, and add anonymous event handlers to handle events where needed, and this is what has been advocated in my class. This seems to be pretty easy to understand, and easy to work with when creating a very simple GUI, but seems to quickly get ugly and cumbersome when making anything other than a very simple gui. Here is a small code sample of what I'm describing: public class FooFrame extends JFrame { JLabel inputLabel; JTextField inputField; JButton fooBtn; JPanel fooPanel; public FooFrame() { super("Foo"); fooPanel = new JPanel(); fooPanel.setLayout(new FlowLayout()); inputLabel = new JLabel("Input stuff"); fooPanel.add(inputLabel); inputField = new JTextField(20); fooPanel.add(inputField); fooBtn = new JButton("Do Foo"); fooBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //handle event } }); fooPanel.add(fooBtn); add(fooPanel, BorderLayout.CENTER); } } Is this type of use of the constructor the best way to code a Swing application in java? If so, what techniques can I use to make sure this type of constructor is organized and maintainable? If not, what is the recommended way to approach putting together a JFrame in java?

    Read the article

  • C++ privately contructed class

    - by Nona Urbiz
    How can I call a function and keep my constructor private? If I make the class static, I need to declare an object name which the compiler uses to call the constructor, which it cannot if the constructor is private (also the object would be extraneous). Here is the code I am attempting to use (it is not compilable): I want to keep the constructor private because I will later be doing a lot of checks before adding an object, modifying previous objects when all submitted variables are not unique rather than creating new objects. #include <iostream> #include <fstream> #include <regex> #include <string> #include <list> #include <map> using namespace std; using namespace tr1; class Referral { public: string url; map<string, int> keywords; static bool submit(string url, string keyword, int occurrences) { //if(Referrals.all.size == 0){ // Referral(url, keyword, occurrences); //} } private: list<string> urls; Referral(string url, string keyword, int occurrences) { url = url; keywords[keyword] = occurrences; Referrals.all.push_back(this); } }; struct All { list<Referral> all; }Referrals; int main() { Referral.submit("url", "keyword", 1); }

    Read the article

  • How to get the parameter names of an object's constructors (reflection)?

    - by Tom
    Say I somehow got an object reference from an other class: Object myObj = anObject; Now I can get the class of this object: Class objClass = myObj.getClass(); Now, I can get all constructors of this class: Constructor[] constructors = objClass.getConstructors(); Now, I can loop every constructor: if (constructors.length > 0) { for (int i = 0; i < constructors.length; i++) { System.out.println(constructors[i]); } } This is already giving me a good summary of the constructor, for example a constructor public Test(String paramName) is shown as public Test(java.lang.String) Instead of giving me the class type however, I want to get the name of the parameter.. in this case "paramName". How would I do that? I tried the following without success: if (constructors.length > 0) { for (int iCon = 0; iCon < constructors.length; iCon++) { Class[] params = constructors[iCon].getParameterTypes(); if (params.length > 0) { for (int iPar = 0; iPar < params.length; iPar++) { Field fields[] = params[iPar].getDeclaredFields(); for (int iFields = 0; iFields < fields.length; iFields++) { String fieldName = fields[i].getName(); System.out.println(fieldName); } } } } } Unfortunately, this is not giving me the expected result. Could anyone tell me how I should do this or what I am doing wrong? Thanks!

    Read the article

  • C++ Why is the converter constructor implicitly called?

    - by ShaChris23
    Why is the Child class's converter constructor called in the code below? I mean, it automatically converts Base to Child via the Child converter constructor. The code below compiles, but shouldn't it not compile since I haven't provided bool Child::operator!=(Base const&)? class Base { }; class Child : public Base { public: Child() {} Child(Base const& base_) : Base(base_) { std::cout <<"should never called!"; } bool operator!=(Child const&) { return true; } }; void main() { Base base; Child child; if(child != base) std::cout << "not equal"; else std::cout << "equal"; }

    Read the article

  • Serialize WPF component using XamlWriter without default constructor

    - by mizipzor
    Ive found out that you can serialize a wpf component, in my example a FixedDocument, using the XamlWriter and a MemoryStream: FixedDocument doc = GetDocument(); MemoryStream stream = new MemoryStream(); XamlWriter.Save(doc, stream); And then to get it back: stream.Seek(0, SeekOrigin.Begin); FixedDocument result = (FixedDocument)XamlReader.Load(stream); return result; However, now I need to be able to serialize a DocumentPage as well. Which lacks a default constructor which makes the XamlReader.Load call throw an exception. Is there a way to serialize a wpf component without a default constructor?

    Read the article

  • Why doesn't Visual Studio show an exception message when my exception occurs in a static constructor

    - by Tim Goodman
    I'm running this C# code in Visual Studio in debug mode: public class MyHandlerFactory : IHttpHandlerFactory { private static Dictionary<string, bool> myDictionary = new Dictionary<string, bool>(); static MyHandlerFactory() { myDictionary.Add("someKey",true); myDictionary.Add("someKey",true); // fails due to duplicate key } } Outside of the static constructor, when I get to the line with the error Visual Studio highlights it and pops up a message about the exception. But in the static constructor I get no such message. I am stepping through line-by-line, so I know that I'm getting to that line and no further. Why is this? (I have no idea if that fact that my class implements IHttpHandlerFactory matters, but I included it just in case.) This is VS2005, .Net 2.0

    Read the article

  • C# Constructor Question

    - by Vaccano
    I have a constructor question for C#. I have this class: public partial class Signature : Form, ISignature { private readonly SignatureMediator mediator; public Signature(SignatureMediator mediator) { this.mediator = mediator; InitializeComponent(); } .... more stuff } I want to construct this class like this: public SignatureMediator(int someValue, int otherValue, int thirdValue) : this(new Signature(this), someValue, otherValue, thirdValue) // This is not allowed --^ { // I don't see anyway to get this in to the ":this" part. //Signature signature = new Signature(this); } public SignatureMediator(ISignature form, int someValue, int otherValue, int thirdValue) { SigForm = form; SomeValue= someValue; OtherValue= otherValue; ThirdValue= thirdValue; } The : this( new SignatureThis(this) is not allowed (the this used in the constructor is not allowed). Is there anyway to set this up without duplicating the assignment of the int values?

    Read the article

  • Activator.CreateInstance(Type) for a type without parameterless constructor

    - by Seb
    Reading existing code at work, I wondered how come this could work. I have a class defined in an assembly : [Serializable] public class A { private readonly string _name; private A(string name) { _name = name; } } And in another assembly : public void f(Type t) { object o = Activator.CreateInstance(t); } and that simple call f(typeof(A)) I expected an exception about the lack of a parameterless constructor because AFAIK, if a ctor is declared, the compiler isn't supposed to generate the default public parameterless constructor. This code runs under .NET 2.0.

    Read the article

  • Class Type Expected error on TableAdapter constructor

    - by Chris Franz
    I am using Delphi Prism to connect to an Advantage Database Server. I created a connection using the server explorer to the database. I added a dataset object to my project and added a table to the dataset. Everything works fine in the IDE, however, I get an error in the generated designer code on the table adapter constructor. The error is: (PE26) Class type expected. Here is the generated code: { Presidents.PresidentsTableAdapters.USPRESIDENTSTableAdapter } constructor Presidents.PresidentsTableAdapters.USPRESIDENTSTableAdapter; begin self.ClearBeforeFill := true; end;

    Read the article

  • Constructor or Explicit cast

    - by Felan
    In working with Linq to Sql I create a seperate class to ferry data to a web page. To simplify creating these ferry objects I either use a specialized constructor or an explicit conversion operator. I have two questions. First which approach is better from a readibility perspective? Second while the clr code that is generated appeared to be the same to me, are there situations where one would be treated different than the other by the compiler (in lambda's or such). Example code (DatabaseFoo uses specialized constructor and BusinessFoo uses explicit operator): public class DatabaseFoo { private static int idCounter; // just to help with generating data public int Id { get; set; } public string Name { get; set; } public DatabaseFoo() { Id = idCounter++; Name = string.Format("Test{0}", Id); } public DatabaseFoo(BusinessFoo foo) { this.Id = foo.Id; this.Name = foo.Name; } } public class BusinessFoo { public int Id { get; set; } public string Name { get; set; } public static explicit operator BusinessFoo(DatabaseFoo foo) { return FromDatabaseFoo(foo); } public static BusinessFoo FromDatabaseFoo(DatabaseFoo foo) { return new BusinessFoo {Id = foo.Id, Name = foo.Name}; } } public class Program { static void Main(string[] args) { Console.WriteLine("Creating the initial list of DatabaseFoo"); IEnumerable<DatabaseFoo> dafoos = new List<DatabaseFoo>() { new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo()}; foreach(DatabaseFoo dafoo in dafoos) Console.WriteLine(string.Format("{0}\t{1}", dafoo.Id, dafoo.Name)); Console.WriteLine("Casting the list of DatabaseFoo to a list of BusinessFoo"); IEnumerable<BusinessFoo> bufoos = from x in dafoos select (BusinessFoo) x; foreach (BusinessFoo bufoo in bufoos) Console.WriteLine(string.Format("{0}\t{1}", bufoo.Id, bufoo.Name)); Console.WriteLine("Creating a new list of DatabaseFoo by calling the constructor taking BusinessFoo"); IEnumerable<DatabaseFoo> fufoos = from x in bufoos select new DatabaseFoo(x); foreach(DatabaseFoo fufoo in fufoos) Console.WriteLine(string.Format("{0}\t{1}", fufoo.Id, fufoo.Name)); } }

    Read the article

  • mockito mock a constructor with parameter

    - by Shengjie
    I have a class as below: public class A { public A(String test) { bla bla bla } public String check() { bla bla bla } } The logic in the constructor A(String test) and check() are the things I am trying to mock. I want any calls like: new A($$$any string$$$).check() returns a dummy string "test". I tried: A a = mock(A.class); when(a.check()).thenReturn("test"); String test = a.check(); // to this point, everything works. test shows as "tests" whenNew(A.class).withArguments(Matchers.anyString()).thenReturn(rk); // also tried: //whenNew(A.class).withParameterTypes(String.class).withArguments(Matchers.anyString()).thenReturn(rk); new A("random string").check(); // this doesn't work But it doesn't seem to be working. new A($$$any string$$$).check() is still going through the constructor logic instead of fetch the mocked object of A.

    Read the article

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