Results 1 to 3 of 3

Thread: [RESOLVED] [2.0] Optional Parameters

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Mar 2006
    Location
    Pennsylvania
    Posts
    1,069

    Resolved [RESOLVED] [2.0] Optional Parameters

    I believe it is possible to have optional parameters in C#. Some programmers will swear by overloading constructors, but in my eyes, less code is easier to understand and just better for me.

    I am aware that there is a question mark.. I guess I would call it.. an operator?

    You can put it after types in variable declarations and stuff of the sort. For example:

    Code:
    private Rectangle? sourceRectangle;
    
    public SpriteToRender(Rectangle? sourceRectangle)
    {
        this.sourceRectangle = sourceRectangle;
    }
    Anyways, that's how I believe it works. I find it rather redundant to create an overload of the constructor multiple times when you can just use the "?" (operator?)

    Anyways, try searching for a "?" on google or msdn. I can't really find any documentation on it! Can anyone explain this (operator?) to me? Is it good to use? My friend who is a game programmer for exDream and Microsoft for a couple projects uses them a lot. Since I know he is a great programmer, I wanted to learn these for myself. Are they good practice? Am I better off just overloading the constructor instead of using these? Are they the equivalent to the "Optional" keyword in VB?

    Thanks a bunch.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2.0] Optional Parameters

    There is no such thing as optional parameters in C#. What you have done there has nothing to do with optional parameters. That is simply using a nullable type. That code is shorthand for this:
    Code:
    private Nullable<Rectangle> sourceRectangle;
    
    public SpriteToRender(Nullable<Rectangle> sourceRectangle)
    {
        this.sourceRectangle = sourceRectangle;
    }
    A nullable type is basically a structure that can have a null value. You should read the MSDN documentation for the Nullable<T> type.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Mar 2006
    Location
    Pennsylvania
    Posts
    1,069

    Re: [2.0] Optional Parameters

    Oh alright. Thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width