Search Results

Search found 597 results on 24 pages for 'constructors'.

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

  • How come the Name property is <Unknown> on a FileStream which uses handle constructors?

    - by Mikael Svenson
    Say you get a file handle from some outside DLL and instantiate a FileStream with it. It works just fine for reading and writing. Then you want the path and name of that handle and try to access the Name property of your FileStream object, and it returns 'unknown'. This is true for the constructors which takes file handles: public FileStream(IntPtr handle, ... public FileStream(SafeFileHandle handle, ... I know the short answer, because it's not implemented. The private field _fileName of FileStream is never assigned in those constructors. Seems the API to get the name from a handle involves more than one line of code, but I still think they could have bothered to include this. So the real questions is: Why haven't they? Or did they just forget?

    Read the article

  • Why would one want to use the public constructors on Boolean and similar immutable classes?

    - by Robert J. Walker
    (For the purposes of this question, let us assume that one is intentionally not using auto(un)boxing, either because one is writing pre-Java 1.5 code, or because one feels that autounboxing makes it too easy to create NullPointerExceptions.) Take Boolean, for example. The documentation for the Boolean(boolean) constructor says: Note: It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory valueOf(boolean) is generally a better choice. It is likely to yield significantly better space and time performance. My question is, why would you ever want to get a new instance in the first place? It seems like things would be simpler if constructors like that were private. For example, if they were, you could write this with no danger (even if myBoolean were null): if (myBoolean == Boolean.TRUE) It'd be safe because all true Booleans would be references to Boolean.TRUE and all false Booleans would be references to Boolean.FALSE. But because the constructors are public, someone may have used them, which means that you have to write this instead: if (Boolean.TRUE.equals(myBoolean)) But where it really gets bad is when you want to check two Booleans for equality. Something like this: if (myBooleanA == myBooleanB) ...becomes this: if ( (myBooleanA == null && myBooleanB == null) || (myBooleanA == null && myBooleanA.equals(myBooleanB)) ) I can't think of any reason to have separate instances of these objects which is more compelling than not having to do the nonsense above. What say you?

    Read the article

  • CArray doesn't call copy constructors on memory reallocations, now what?

    - by MMx
    Suppose I have a class that requires copy constructor to be called to make a correct copy of: struct CWeird { CWeird() { number = 47; target = &number; } CWeird(const CWeird &other) : number(other.number), target(&number) { } void output() { printf("%d %d\n", *target, number); } int *target, number; }; Now the trouble is that CArray doesn't call copy constructors on its elements when reallocating memory (only memcpy from the old memory to the new), e.g. this code CArray<CWeird> a; a.SetSize(1); a[0].output(); a.SetSize(2); a[0].output(); results in 47 47 -572662307 47 I don't get this. Why is it that std::vector can copy the same objects properly and CArray can't? What's the lesson here? Should I use only classes that don't require explicit copy constructors? Or is it a bad idea to use CArray for anything serious?

    Read the article

  • Does code in the constructor add to code in subclass constructors?

    - by Jeremy Rudd
    Does code in the constructor add to code in subclass constructors? Or does the subclass's constructor override the superclass? Given this example superclass constructor: class Car{ function Car(){ trace("CAR") } } ...and this subclass constructor: class FordCar extends Car{ function FordCar(){ trace("FORD") } } When an instance of FordCar is created, will this trace "Car" and "Ford" ??

    Read the article

  • How to define an aspectj pointcut that picks out all constructors of a class that has a specific annotation?

    - by PineForest
    Here is the annotation: @Target(value = ElementType.TYPE) @Retention(value = RetentionPolicy.RUNTIME) @Inherited public @interface MyAnnotation { String name(); } Here is one annotated class: @MyAnnotation(name="foo") public class ClassA { public ClassA() { // Do something } } Here is a second annotated class: @MyAnnotation(name="bar") public class ClassB { public ClassB(String aString) { // Do something } } I am looking for an aspectj pointcut that correctly matches the constructors for ClassA and ClassB while not matching any other constructor for any other class NOT annotated by MyAnnotation.

    Read the article

  • C++, constructor restrictions

    - by Pie86
    Hi everybaody, I'm studing C++ and I can't understand the meaning of the boldface sentence below: From IBM manual: The following restrictions apply to constructors and destructors: Constructors and destructors do not have return types nor can they return values. References and pointers cannot be used on constructors and destructors because their addresses cannot be taken. Constructors cannot be declared with the keyword virtual. Constructors and destructors cannot be declared static, const, or volatile. Unions cannot contain class objects that have constructors or destructors. Could you please provide me an example? Thank you!

    Read the article

  • Do you put a super() call a the beginning of your constructors?

    - by sleske
    This is a question about coding style and recommended practices: As explained in the answers to the question unnecessary to put super() in constructor?, if you write a constructor for a class that is supposed to use the default (no-arg) constructor from the superclass, you may call super() at the beginning of your constructor: public MyClass(int parm){ super(); // leaving this out makes no difference // do stuff... } but you can also omit the call; the compiler will in both cases act as if the super() call were there. So then, do you put the call into your constructors or not? On the one hand, one might argue that including the super() makes things more explicit. OTOH, I always dislike writing redundant code, so personally I tend to leave it out; I do however regularly see it in code from others. What are your experiences? Did you have problems with one or the other approach? Do you have coding guidelines which prescribe one approach?

    Read the article

  • When using Dependency Injection with StructureMap how do I chooose among multiple constructors?

    - by Mark Rogers
    I'm trying to get structuremap to build Fluent Nhibernate's SessionSource object for some of my intregration tests. The only problem is that Fluent's concrete implementation of ISessionSource (SessionSource) has 3 constructors: public SessionSource(PersistenceModel model) { Initialize(new Configuration().Configure(), model); } public SessionSource(IDictionary<string, string> properties, PersistenceModel model) { Initialize(new Configuration().AddProperties(properties), model); } public SessionSource(FluentConfiguration config) { configuration = config.Configuration; sessionFactory = config.BuildSessionFactory(); dialect = Dialect.GetDialect(configuration.Properties); } I've tried configuring my ObjectFactory supplying an argument for the first constructor but it seems like it wants to try the second one. How do I configure my ObjectFactory so that I can choose the first constructor or perhaps even another one if I decide to use that?

    Read the article

  • Access of private field of another object in copy constructors - Really a problem?

    - by DR
    In my Java application I have some copy-constructors like this public MyClass(MyClass src) { this.field1 = src.field1; this.field2 = src.field2; this.field3 = src.field3; ... } Now Netbeans 6.9 warns about this and I wonder what is wrong with this code? My concerns: Using the getters might introduce unwanted side-effects. The new object might no longer be considered a copy of the original. If it is recommended using the getters, wouldn't it be more consistent if one would use setters for the new instance as well?

    Read the article

  • C# - Why can't I enforce derived classes to have parameterless constructors?

    - by FrisbeeBen
    I am trying to do the following: public class foo<T> where T : bar, new { _t = new T(); private T _t; } public abstract class bar { public abstract void someMethod(); // Some implementation } public class baz : bar { public overide someMethod(){//Implementation} } And I am attempting to use it as follows: foo<baz> fooObject = new foo<baz>(); And I get an error explaining that 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method. I fully understand why this must be, and also understand that I could pass a pre-initialized object of type 'T' in as a constructor argument to avoid having to 'new' it, but is there any way around this? any way to enforce classes that derive from 'bar' to supply parameterless constructors?

    Read the article

  • Why can't I enforce derived classes to have parameterless constructors?

    - by FrisbeeBen
    I am trying to do the following: public class foo<T> where T : bar, new() { public foo() { _t = new T(); } private T _t; } public abstract class bar { public abstract void someMethod(); // Some implementation } public class baz : bar { public overide someMethod(){//Implementation} } And I am attempting to use it as follows: foo<baz> fooObject = new foo<baz>(); And I get an error explaining that 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method. I fully understand why this must be, and also understand that I could pass a pre-initialized object of type 'T' in as a constructor argument to avoid having to 'new' it, but is there any way around this? any way to enforce classes that derive from 'bar' to supply parameterless constructors?

    Read the article

  • beginning oop php question: do constructors take the place of getter?

    - by Joel
    I'm working through this tutorial: http://www.killerphp.com/tutorials/object-oriented-php/php-objects-page-3.php At first he has you create a setter and getter method in the class: <?php class person{ var $name; function set_name($new_name){ $this->name=$new_name; } function get_name(){ return $this->name; } } php?> And then you create the object and echo the results: <?php $stefan = new person(); $jimmy = new person(); $stefan ->set_name("Stefan Mischook"); $jimmy ->set_name("Nick Waddles"); echo "The first Object name is: ".$stefan->get_name(); echo "The second Object name is: ".$jimmy->get_name(); ?> Works as expected, and I understand. Then he introduces constructors: class person{ var $name; function __construct($persons_name) { $this->name = $persons_name; } function set_name($new_name){ $this->name=$new_name; } function get_name(){ return $this->name; } } And returns like so: <?php $joel = new person("Joel"); echo "The third Object name is: ".$joel->get_name(); ?> This is all fine and makes sense. Then I tried to combine the two and got an error, so I'm curious-is a constructor always taking the place of a "get" function? If you have a constructor, do you always need to include an argument when creating an object? Gives errors: <?php $stefan = new person(); $jimmy = new person(); $joel = new person("Joel Laviolette"); $stefan ->set_name("Stefan Mischook"); $jimmy ->set_name("Nick Waddles"); echo "The first Object name is: ".$stefan->get_name(); echo "The second Object name is: ".$jimmy->get_name(); echo "The third Object name is: ".$joel->get_name(); ?>

    Read the article

  • C#: Object having two constructors: how to limit which properties are set together?

    - by Dr. Zim
    Say you have a Price object that accepts either an (int quantity, decimal price) or a string containing "4/$3.99". Is there a way to limit which properties can be set together? Feel free to correct me in my logic below. The Test: A and B are equal to each other, but the C example should not be allowed. Thus the question How to enforce that all three parameters are not invoked as in the C example? AdPrice A = new AdPrice { priceText = "4/$3.99"}; // Valid AdPrice B = new AdPrice { qty = 4, price = 3.99m}; // Valid AdPrice C = new AdPrice { qty = 4, priceText = "2/$1.99", price = 3.99m};// Not The class: public class AdPrice { private int _qty; private decimal _price; private string _priceText; The constructors: public AdPrice () : this( qty: 0, price: 0.0m) {} // Default Constructor public AdPrice (int qty = 0, decimal price = 0.0m) { // Numbers only this.qty = qty; this.price = price; } public AdPrice (string priceText = "0/$0.00") { // String only this.priceText = priceText; } The Methods: private void SetPriceValues() { var matches = Regex.Match(_priceText, @"^\s?((?<qty>\d+)\s?/)?\s?[$]?\s?(?<price>[0-9]?\.?[0-9]?[0-9]?)"); if( matches.Success) { if (!Decimal.TryParse(matches.Groups["price"].Value, out this._price)) this._price = 0.0m; if (!Int32.TryParse(matches.Groups["qty"].Value, out this._qty)) this._qty = (this._price > 0 ? 1 : 0); else if (this._price > 0 && this._qty == 0) this._qty = 1; } } private void SetPriceString() { this._priceText = (this._qty > 1 ? this._qty.ToString() + '/' : "") + String.Format("{0:C}",this.price); } The Accessors: public int qty { get { return this._qty; } set { this._qty = value; this.SetPriceString(); } } public decimal price { get { return this._price; } set { this._price = value; this.SetPriceString(); } } public string priceText { get { return this._priceText; } set { this._priceText = value; this.SetPriceValues(); } } }

    Read the article

  • Why default constructor does not appear for value types?

    - by Arun
    The below snippet gives me a list of constructors and methods of a type. static void ReflectOnType(Type type) { Console.WriteLine(type.FullName); Console.WriteLine("------------"); List<ConstructorInfo> constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |BindingFlags.Instance | BindingFlags.Default).ToList(); List<MethodInfo> methods = type.GetMethods().ToList(); Type baseType = type.BaseType; while (baseType != null) { constructors.AddRange(baseType.GetConstructors(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default)); methods.AddRange(baseType.GetMethods()); baseType = baseType.BaseType; } Console.WriteLine("Reflection on {0} type", type.Name); for (int i = 0; i < constructors.Count; i++) { Console.Write("Constructor: {0}.{1}", constructors[i].DeclaringType.Name, constructors[i].Name); Console.Write("("); ParameterInfo[] parameterInfos = constructors[i].GetParameters(); if (parameterInfos.Length > 0) { for (int j = 0; j < parameterInfos.Length; j++) { if (j > 0) { Console.Write(", "); } Console.Write("{0} {1}", parameterInfos[j].ParameterType, parameterInfos[j].Name); } } Console.Write(")"); if (constructors[i].IsSpecialName) { Console.Write(" has 'SpecialName' attribute"); } Console.WriteLine(); } Console.WriteLine(); for (int i = 0; i < methods.Count; i++) { Console.Write("Method: {0}.{1}", methods[i].DeclaringType.Name, methods[i].Name); // Determine whether or not each field is a special name. if (methods[i].IsSpecialName) { Console.Write(" has 'SpecialName' attribute"); } Console.WriteLine(); } } But when I pass an ‘int’ type to this method, why don’t I see the implicit constructor in the output? Or, how do I modify the above code to list the default constructor as well (in case I’m missing something in my code).

    Read the article

  • I need to implement C# deep copy constructors with inheritance. What patterns are there to choose fr

    - by Tony Lambert
    I wish to implement a deepcopy of my classes hierarchy in C# public Class ParentObj : ICloneable { protected int myA; public virtual Object Clone () { ParentObj newObj = new ParentObj(); newObj.myA = theObj.MyA; return newObj; } } public Class ChildObj : ParentObj { protected int myB; public override Object Clone ( ) { Parent newObj = this.base.Clone(); newObj.myB = theObj.MyB; return newObj; } } This will not work as when Cloning the Child only a parent is new-ed. In my code some classes have large hierarchies. What is the recommended way of doing this? Cloning everything at each level without calling the base class seems wrong? There must be some neat solutions to this problem, what are they? Can I thank everyone for their answers. It was really interesting to see some of the approaches. I think it would be good if someone gave an example of a reflection answer for completeness. +1 awaiting!

    Read the article

  • Pass Session data to a Class Library without using a bunch of constructors?

    - by sah302
    Hi all, I've got my application here where literally every object has a lastUpdatedBy property. The information I put into here is the person's username, which is retrieved from the session("username") variable. How can I pass this data to my DAL in the class library? At first I was just passing in the value into each method, but this is ridiculous I thought, there should be no reason to do that every time a method is called. Then I thought well if I just put it in a constructor for each of the DAL related classes, that will make it even easier. However, even still on any given page, I've got a plethora of New() declarations, for which every single line I need to pass in the session username casted as a string. Is there an even still more efficient way of doing this so that I could only declare this in one place, and everything will know what it is and I can pass it to classes in a class library?

    Read the article

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