Can I tell the interface to default the properties I don't supply to null? What would let me do this

No. You cannot provide default values for interfaces or type aliases as they are compile time only and default values need runtime support

Alternative

But values that are not specified default to undefined in JavaScript runtimes. So you can mark them as optional:

interface IX {
  a: string,
  b?: any,
  c?: AnotherType
}

And now when you create it you only need to provide a:

let x: IX = {
    a: 'abc'
};

You can provide the values as needed:

x.a = 'xyz'
x.b = 123
x.c = new AnotherType()
Answer from basarat on Stack Overflow
🌐
Technical Feeder
technicalfeeder.com › 2022 › 08 › typescript-how-to-set-a-default-value-with-interface
TypeScript How to set a default value with Interface | Technical Feeder
October 26, 2022 - const MyInterfaceDefault: MyInterface = { a: 0, b: "default-string", c: null, }; const data1: MyInterface = { ...MyInterfaceDefault, c: "something", }; const data2: MyInterface = { ...MyInterfaceDefault, c: { value: 1 }, }; console.log(data1); // { a: 0, b: 'default-string', c: 'something' } console.log(data2); // { a: 0, b: 'default-string', c: { value: 1 } } Please check the following article if you still don’t know about the three dots called spread operator. TypeScript/JavaScript Spread operator (three dots) The spread operator (three dots) is used to copy an array and expand an array to pass the values to another object or function parameters. It can also be used as rest parameters in a function to indicate that the function can take as many arguments as you want.
🌐
Reddit
reddit.com › r/csharp › is it possible to define default properties for an interface?
r/csharp on Reddit: Is it possible to define default properties for an interface?
July 22, 2024 -

I am using SWIG to generate csharp bindings for some C++ code. I was hoping to write an Interface that wraps the bindings, for convenience. My interface currently looks similar to this:

namespace GameName
{

    public interface PlayerInterface
    {

        public byte Id
        {
            get
            {
                return Game.Players[this].id;
            }
            set
            {
                Game.Players[this].id = value;
            }
        }

        public byte Score
        {
            get
            {
                return Game.Players[this].score;
            }
            set
            {
                Game.Players[this].score= value;
            }
        }
    }
}

Game.Players is map from csharp objects to objects generated by SWIG.

When compiling, my class that implements the interface yields `The name 'Id' does not exist in the current context` (Same for Score)

These docs seem to indicate that providing explicit default properties is possible: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/interface-properties

The example in the docs seems incomplete. Is it possible to do what I'm asking?

🌐
Blogger
jeremybytes.blogspot.com › 2019 › 09 › c-8-interfaces-properties-and-default.html
Jeremy Bytes: C# 8 Interfaces: Properties and Default Implementation
September 24, 2019 - Hi Jeremy, a default implementation for a property setter makes sense if it refers to other properties that are already in the interface. In your example. you could have this default property: `double SideLengthInInch { get => SideLength / 2.54; set => SideLength = value * 2.54; } ` ReplyDelete
🌐
Reddit
reddit.com › r/csharp › generic interface with property can't set default value?
r/csharp on Reddit: Generic interface with property can't set default value?
April 21, 2023 -

In the following two interfaces:

public interface Defaultable
{
    public static object Default { get; } = new object();
}

public interface Defaultable<T> : Defaultable
{
    public static T Default { get; } = new T();
}

The top one works fine, but the bottom one throws an error:

Cannot create an instance of the variable type 'T' because it does not have the new() constraint

Why can I have a default value in non-generic interfaces, but not generic ones?

Edit: I should specify that I have nullable enabled, and I do not want the properties to be able to return null (default being a Null Object Pattern of sorts).

🌐
TestMu AI Community
community.testmuai.com › ask a question
Defaulting Unspecified Interface Properties to Null in TypeScript - Ask a Question - TestMu AI Community
July 25, 2024 - I have the following TypeScript interface: interface IX { a: string; b: any; c: AnotherType; } I declare a variable of this type and initialize all the properties with default values: let x: IX = { a: 'abc', b: null, c: null }; Later, I assign actual values to these properties in an init function: x.a = 'xyz'; x.b = 123; x.c = new AnotherType(); I don’t like having to specify default null values for each property when declaring the object, especially since they will...
Top answer
1 of 6
270

Virtuals may have defaults. The defaults in the base class are not inherited by derived classes.

Which default is used -- ie, the base class' or a derived class' -- is determined by the static type used to make the call to the function. If you call through a base class object, pointer or reference, the default denoted in the base class is used. Conversely, if you call through a derived class object, pointer or reference the defaults denoted in the derived class are used. There is an example below the Standard quotation that demonstrates this.

Some compilers may do something different, but this is what the C++03 and C++11 Standards say:

8.3.6.10:

A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides. Example:

struct A {
  virtual void f(int a = 7);
};
struct B : public A {
  void f(int a);
};
void m()
{
  B* pb = new B;
  A* pa = pb;
  pa->f(); //OK, calls pa->B::f(7)
  pb->f(); //error: wrong number of arguments for B::f()
}

Here is a sample program to demonstrate what defaults are picked up. I'm using structs here rather than classes simply for brevity -- class and struct are exactly the same in almost every way except default visibility.

#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>

using std::stringstream;
using std::string;
using std::cout;
using std::endl;

struct Base { virtual string Speak(int n = 42); };
struct Der : public Base { string Speak(int n = 84); };

string Base::Speak(int n) 
{ 
    stringstream ss;
    ss << "Base " << n;
    return ss.str();
}

string Der::Speak(int n)
{
    stringstream ss;
    ss << "Der " << n;
    return ss.str();
}

int main()
{
    Base b1;
    Der d1;

    Base *pb1 = &b1, *pb2 = &d1;
    Der *pd1 = &d1;
    cout << pb1->Speak() << "\n"    // Base 42
        << pb2->Speak() << "\n"     // Der 42
        << pd1->Speak() << "\n"     // Der 84
        << endl;
}

The output of this program (on MSVC10 and GCC 4.4) is:

Base 42
Der 42
Der 84
2 of 6
55

This was the topic of one of Herb Sutter's early Guru of the Week posts.

The first thing he says on the subject is DON'T DO THAT.

In more detail, yes, you can specify different default parameters. They won't work the same way as the virtual functions. A virtual function is called on the dynamic type of the object, while the default parameter values are based on the static type.

Given

class A {
    virtual void foo(int i = 1) { cout << "A::foo" << i << endl; }
};
class B: public A {
    virtual void foo(int i = 2) { cout << "B::foo" << i << endl; }
};
void test() {
A a;
B b;
A* ap = &b;
a.foo();
b.foo();
ap->foo();
}

you should get A::foo1 B::foo2 B::foo1

🌐
Michael-mckenna
michael-mckenna.com › optional-arguments-in-c-sharp-interfaces
Optional arguments in C# interfaces - Michael McKenna
August 15, 2016 - In the interest of code-safety I don’t put default values on implementing classes any more.
Find elsewhere
🌐
Tomdupont
tomdupont.net › 2016 › 01 › csharp-interfaces-and-default-parameters.html
C# Interfaces and Default Parameters - Tom DuPont .NET
January 22, 2016 - So, now that you know how the trick ... default value for a parameter defined by an interface and a class? The answer is simple: if your object is cast as the class, then it will use the class value. If your object is cast as the interface, ...
🌐
UiPath Community
forum.uipath.com › feedback › studio
Changing argument name pushes its default value to all related invoke interface - Studio - UiPath Community Forum
May 10, 2023 - Let’s say I have a workfile A with input argument “ArgA” and I set default value “valueA” (just for when I want to test only workfile A). Workfile A is invoked by workfile B, C and D, and the value they pass for input argument “ArgA” is respectively “valueB”, “valueC”, and “valueD”. If I decide to change the input argument name of workfile A from “ArgA” to “ArguA”, I noticed that instead of just : updating the input argument name in the invoke interfaces in workfile B, C and D, and removing ...
🌐
Unreal Engine
forums.unrealengine.com › development › programming & scripting
C++ Interface w/ default implementation that's usable in C++ and BP - Programming & Scripting - Epic Developer Community Forums
November 21, 2023 - Hi all, I have a custom damage interface that I like to use. Problem is, I currently can’t use it in Blueprints with default implementation it seems. Is there a way to get around this somehow? What would be the best thing I could do to get it so I can have interfaces with default impelementations ...
🌐
Andrew Lock
andrewlock.net › understanding-default-interface-methods
Understanding C# 8 default interface methods
January 30, 2024 - Prior to C# 8, you couldn't do that, and what's more, it also didn't really make sense. interfaces were literally that: definitions of the API/interface a type must implement. If you wanted to provide a "default" implementation, then you had to use an abstract class instead, which limited you in other ways.
🌐
Daveaglick
daveaglick.com › posts › default-interface-members-and-inheritance
Dave Glick - Default Interface Members and Inheritance
September 6, 2019 - That means in the code above for the abstract Toyota base class I would've had to write one of these: public int Cylinders => 4 to implement the interface property and provide a default value, forcing the property into the inheritance chain of Toyota.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › csharp › programming-guide › classes-and-structs › interface-properties
Interface Properties - C# | Microsoft Learn
October 26, 2024 - Defining a default implementation for a property in an interface is rare because interfaces can't define instance data fields.
Top answer
1 of 16
393

Wow, everybody is such a pessimist around here. The answer is yes.

It ain't trivial: by the end, we'll have the core function, a supporting struct, a wrapper function, and a macro around the wrapper function. In my work I have a set of macros to automate all this; once you understand the flow it'll be easy for you to do the same.

I've written this up elsewhere, so here's a detailed external link to supplement the summary here: http://modelingwithdata.org/arch/00000022.htm

We'd like to turn

double f(int i, double x)

into a function that takes defaults (i=8, x=3.14). Define a companion struct:

typedef struct {
    int i;
    double x;
} f_args;

Rename your function f_base, and define a wrapper function that sets defaults and calls the base:

double var_f(f_args in){
    int i_out = in.i ? in.i : 8;
    double x_out = in.x ? in.x : 3.14;
    return f_base(i_out, x_out);
}

Now add a macro, using C's variadic macros. This way users don't have to know they're actually populating a f_args struct and think they're doing the usual:

#define f(...) var_f((f_args){__VA_ARGS__});

OK, now all of the following would work:

f(3, 8);      //i=3, x=8
f(.i=1, 2.3); //i=1, x=2.3
f(2);         //i=2, x=3.14
f(.x=9.2);    //i=8, x=9.2

Check the rules on how compound initializers set defaults for the exact rules.

One thing that won't work: f(0), because we can't distinguish between a missing value and zero. In my experience, this is something to watch out for, but can be taken care of as the need arises---half the time your default really is zero.

I went through the trouble of writing this up because I think named arguments and defaults really do make coding in C easier and even more fun. And C is awesome for being so simple and still having enough there to make all this possible.

2 of 16
197

Yes. :-) But not in a way you would expect.

int f1(int arg1, double arg2, char* name, char *opt);

int f2(int arg1, double arg2, char* name)
{
  return f1(arg1, arg2, name, "Some option");
}

Unfortunately, C doesn't allow you to overload methods so you'd end up with two different functions. Still, by calling f2, you'd actually be calling f1 with a default value. This is a "Don't Repeat Yourself" solution, which helps you to avoid copying/pasting existing code.

🌐
Irisclasson
irisclasson.com › 2013 › 12 › 29 › is-use-of-default-parametersoptional-arguments-a-bad-practice-in-c-q263
Is use of default parameters/optional arguments a bad practice in C#? (Q263)
December 29, 2013 - Optional arguments should not be confused for the param arrays (allows you to pass n number of arguments to a method)- we are talking about two completely different things and it is important to understand the difference. If you don’t know how manyarguments the user will pass in, use a param array, if you need to set default values, use optional arguments.