kandi background
Explore Kits

runtime | platform runtime for cloud , mobile , desktop , and IoT apps

 by   dotnet C# Version: v7.0.0-preview.3.22175.4 License: Non-SPDX

 by   dotnet C# Version: v7.0.0-preview.3.22175.4 License: Non-SPDX

Download this library from

kandi X-RAY | runtime Summary

runtime is a C# library. runtime has no bugs and it has medium support. However runtime has 1 vulnerabilities and it has a Non-SPDX License. You can download it from GitHub.
Official Starting Page: https://dotnet.microsoft.com.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • runtime has a medium active ecosystem.
  • It has 8762 star(s) with 3033 fork(s). There are 382 watchers for this library.
  • There were 8 major release(s) in the last 12 months.
  • There are 7950 open issues and 39285 have been closed. On average issues are closed in 164 days. There are 238 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of runtime is v7.0.0-preview.3.22175.4
runtime Support
Best in #C#
Average in #C#
runtime Support
Best in #C#
Average in #C#

quality kandi Quality

  • runtime has no bugs reported.
runtime Quality
Best in #C#
Average in #C#
runtime Quality
Best in #C#
Average in #C#

securitySecurity

  • runtime has 1 vulnerability issues reported (0 critical, 1 high, 0 medium, 0 low).
runtime Security
Best in #C#
Average in #C#
runtime Security
Best in #C#
Average in #C#

license License

  • runtime has a Non-SPDX License.
  • Non-SPDX licenses can be open source with a non SPDX compliant license, or non open source licenses, and you need to review them closely before use.
runtime License
Best in #C#
Average in #C#
runtime License
Best in #C#
Average in #C#

buildReuse

  • runtime releases are available to install and integrate.
runtime Reuse
Best in #C#
Average in #C#
runtime Reuse
Best in #C#
Average in #C#
Top functions reviewed by kandi - BETA

kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here

Get all kandi verified functions for this library.

Get all kandi verified functions for this library.

runtime Key Features

How to use .NET (with VS, VS Code, command-line CLI) Install official releases Install daily builds Documentation (Get Started, Tutorials, Porting from .NET Framework, API reference, ...) Deploying apps Supported OS versions

Roadmap

Releases

Why do Switch and ListView controls in MAUI not update with 2-way binding?

copy iconCopydownload iconDownload
<ListView x:Name="listView" ItemsSource="{Binding Items}"
        SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
        VerticalOptions="Start"
        ItemSelected="ItemSelected">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding}" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Android app won't build -- The minCompileSdk (31) specified in a dependency's androidx.work:work-runtime:2.7.0-beta01

copy iconCopydownload iconDownload
dependencies {
    def work_version = "2.6.0"
    // Force WorkManager 2.6.0 for transitive dependency
    implementation("androidx.work:work-runtime-ktx:$work_version") {
        force = true
    }
}
   > A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
      > The minCompileSdk (31) specified in a
        dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
        is greater than this module's compileSdkVersion (android-30).
        Dependency: androidx.core:core-ktx:1.7.0-alpha02.
configurations.all {
    resolutionStrategy { force 'androidx.core:core-ktx:1.6.0' }
}
   > A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
      > The minCompileSdk (31) specified in a
        dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
        is greater than this module's compileSdkVersion (android-30).
        Dependency: androidx.core:core-ktx:1.7.0-alpha02.
configurations.all {
    resolutionStrategy { force 'androidx.core:core-ktx:1.6.0' }
}
api(group: "androidx.work", name: "work-runtime") {
    version {
        strictly "2.7.0-alpha04"
    }
}
implementation "androidx.core:core-ktx:+" 
implementation "androidx.core:core-ktx:1.6.0"
implementation "androidx.core:core-ktx:+" ->

implementation "androidx.core:core-ktx:1.6.0" 
implementation "androidx.core:core-ktx:+" 
implementation "androidx.core:core-ktx:1.6.0"
implementation "androidx.core:core-ktx:+" ->

implementation "androidx.core:core-ktx:1.6.0" 
implementation "androidx.core:core-ktx:+" 
implementation "androidx.core:core-ktx:1.6.0"
implementation "androidx.core:core-ktx:+" ->

implementation "androidx.core:core-ktx:1.6.0" 
configurations.all {
        resolutionStrategy { force 'androidx.work:work-runtime:2.6.0' }
    }
android {
 defaultConfig {
   //here
 }
}
configurations.all {
        resolutionStrategy { force 'androidx.work:work-runtime:2.6.0' }
    }
android {
 defaultConfig {
   //here
 }
}
dependencies{
implementation 'androidx.work:work-runtime-ktx:2.6.0'
}
implementation 'androidx.core:core-ktx:1.7.0'  and `api 'com.google.android.material:material:1.4.0-alpha07'`
implementation 'androidx.core:core-ktx:1.6.0' and api 'com.google.android.material:material:1.4.0-alpha06'
implementation 'androidx.core:core-ktx:1.7.0'  and `api 'com.google.android.material:material:1.4.0-alpha07'`
implementation 'androidx.core:core-ktx:1.6.0' and api 'com.google.android.material:material:1.4.0-alpha06'
// build.gradle (Module:testApp)

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "myproject.name.testApp"
        minSdkVersion 16 // <--- must be same as under dependencies section
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.6.0' // <--- Was showing 1.7, it fix problem
    implementation 'androidx.appcompat:appcompat:1.3.1'
implementation "androidx.paging:paging-compose:1.0.0-alpha10"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.activity:activity-compose:1.3.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
implementation "androidx.paging:paging-compose:1.0.0-alpha10"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.activity:activity-compose:1.3.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.core:core-ktx:1.6.0'
 implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
 implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
Dependency: androidx.appcompat:appcompat:1.4.0.
dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.0'
    ...
    ...
    ...

    /* The minCompileSdk (31) specified in a
    dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
    is greater than this module's compileSdkVersion (android-30).
    Dependency: androidx.appcompat:appcompat:1.4.0.  */

}
Dependency: androidx.appcompat:appcompat:1.4.0.
dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.0'
    ...
    ...
    ...

    /* The minCompileSdk (31) specified in a
    dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
    is greater than this module's compileSdkVersion (android-30).
    Dependency: androidx.appcompat:appcompat:1.4.0.  */

}
    compileSdkVersion 29

    targetSdkVersion 29

    implementation 'com.google.android.gms:play-services-ads-lite:20.5.0'

configurations.all {
    resolutionStrategy { force 'androidx.work:work-runtime:2.6.0' }
    resolutionStrategy { force 'androidx.core:core-ktx:1.6.0' }
}
    compileSdkVersion 29

    targetSdkVersion 29

    implementation 'com.google.android.gms:play-services-ads-lite:20.5.0'

configurations.all {
    resolutionStrategy { force 'androidx.work:work-runtime:2.6.0' }
    resolutionStrategy { force 'androidx.core:core-ktx:1.6.0' }
}
 implementation 'androidx.core:core-ktx:1.7.0'
 implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.0'
 implementation 'androidx.core:core-ktx:1.7.0'
 implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.0'
android {
compileSdkVersion 31 // Changed to 31

sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
}

defaultConfig {
    applicationId "com.example.blah_blah"
    minSdkVersion 16
    targetSdkVersion 31  //Changed to 31
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

buildTypes {
    release {
        // TODO: Add your own signing config for the release build.
        // Signing with the debug keys for now, so `flutter run --release` works.
        signingConfig signingConfigs.debug
    }
}
buildscript {
ext.kotlin_version = '1.6.10' //change here
repositories {
    google()
    jcenter()
}

dependencies {
    classpath 'com.android.tools.build:gradle:4.1.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
android {
compileSdkVersion 31 // Changed to 31

sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
}

defaultConfig {
    applicationId "com.example.blah_blah"
    minSdkVersion 16
    targetSdkVersion 31  //Changed to 31
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

buildTypes {
    release {
        // TODO: Add your own signing config for the release build.
        // Signing with the debug keys for now, so `flutter run --release` works.
        signingConfig signingConfigs.debug
    }
}
buildscript {
ext.kotlin_version = '1.6.10' //change here
repositories {
    google()
    jcenter()
}

dependencies {
    classpath 'com.android.tools.build:gradle:4.1.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
configurations.all {
        resolutionStrategy { force 'androidx.work:work-runtime:2.6.0' }
    }
android {
 defaultConfig {
   //here
 }
}
configurations.all {
        resolutionStrategy { force 'androidx.work:work-runtime:2.6.0' }
    }
android {
 defaultConfig {
   //here
 }
}
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'

Flutter iOS Error Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libamsupport.dylib (0x203913130)

copy iconCopydownload iconDownload
    Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported
    deployment target versions is 9.0 to 15.2.99. (in target 'AppAuth' from project 'Pods')
    /Users/zack/Desktop/halseon/Merchant/halseon_merchants/ios/Pods/Pods.xcodeproj: warning: The iOS
    Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported
    deployment target versions is 9.0 to 15.2.99. (in target 'GoogleSignIn' from project 'Pods')
$ rm ios/Flutter/Flutter.podspec
$ flutter clean
flutter clean
rm -Rf ios/Pods
rm -Rf ios/.symlinks
rm -Rf ios/Flutter/Flutter.framework
rm -Rf ios/Flutter/Flutter.podspec
rm ios/Podfile
cd ios
flutter pub get
pod cache clean --all
pod install

    or  (below for m1 chip incase above command thrown error in pod install)

#1 Install ffi
sudo arch -x86_64 gem install ffi

#2 Re-install dependencies
arch -x86_64 pod install
1. Open ios/Pods/Pods.xcodeproj in Xcode
2. Change the iOS Deployment info from 8.0 to 9.0
From xcode clean / build again / run. Hope this should work. Before please confirm whether all the build settings for iOS configured properly or not.
Check platform :ios, '10.0' is uncommented
target 'CustomImageNotifications' do
  use_frameworks!
  pod 'Firebase/Analytics'
  pod 'Firebase/Messaging'
end 
flutter clean
rm -Rf ios/Pods
rm -Rf ios/.symlinks
rm -Rf ios/Flutter/Flutter.framework
rm -Rf ios/Flutter/Flutter.podspec
rm ios/Podfile
cd ios
flutter pub get
pod cache clean --all
pod install

    or  (below for m1 chip incase above command thrown error in pod install)

#1 Install ffi
sudo arch -x86_64 gem install ffi

#2 Re-install dependencies
arch -x86_64 pod install
1. Open ios/Pods/Pods.xcodeproj in Xcode
2. Change the iOS Deployment info from 8.0 to 9.0
From xcode clean / build again / run. Hope this should work. Before please confirm whether all the build settings for iOS configured properly or not.
Check platform :ios, '10.0' is uncommented
target 'CustomImageNotifications' do
  use_frameworks!
  pod 'Firebase/Analytics'
  pod 'Firebase/Messaging'
end 
flutter clean
rm -Rf ios/Pods
rm -Rf ios/.symlinks
rm -Rf ios/Flutter/Flutter.framework
rm -Rf ios/Flutter/Flutter.podspec
rm ios/Podfile
cd ios
flutter pub get
pod cache clean --all
pod install

    or  (below for m1 chip incase above command thrown error in pod install)

#1 Install ffi
sudo arch -x86_64 gem install ffi

#2 Re-install dependencies
arch -x86_64 pod install
1. Open ios/Pods/Pods.xcodeproj in Xcode
2. Change the iOS Deployment info from 8.0 to 9.0
From xcode clean / build again / run. Hope this should work. Before please confirm whether all the build settings for iOS configured properly or not.
Check platform :ios, '10.0' is uncommented
target 'CustomImageNotifications' do
  use_frameworks!
  pod 'Firebase/Analytics'
  pod 'Firebase/Messaging'
end 
flutter clean
rm -Rf ios/Pods
rm -Rf ios/.symlinks
rm -Rf ios/Flutter/Flutter.framework
rm -Rf ios/Flutter/Flutter.podspec
rm ios/Podfile
cd ios
flutter pub get
pod cache clean --all
pod install

    or  (below for m1 chip incase above command thrown error in pod install)

#1 Install ffi
sudo arch -x86_64 gem install ffi

#2 Re-install dependencies
arch -x86_64 pod install
1. Open ios/Pods/Pods.xcodeproj in Xcode
2. Change the iOS Deployment info from 8.0 to 9.0
From xcode clean / build again / run. Hope this should work. Before please confirm whether all the build settings for iOS configured properly or not.
Check platform :ios, '10.0' is uncommented
target 'CustomImageNotifications' do
  use_frameworks!
  pod 'Firebase/Analytics'
  pod 'Firebase/Messaging'
end 
flutter clean
rm -Rf ios/Pods
rm -Rf ios/.symlinks
rm -Rf ios/Flutter/Flutter.framework
rm -Rf ios/Flutter/Flutter.podspec
rm ios/Podfile
cd ios
flutter pub get
pod cache clean --all
pod install

    or  (below for m1 chip incase above command thrown error in pod install)

#1 Install ffi
sudo arch -x86_64 gem install ffi

#2 Re-install dependencies
arch -x86_64 pod install
1. Open ios/Pods/Pods.xcodeproj in Xcode
2. Change the iOS Deployment info from 8.0 to 9.0
From xcode clean / build again / run. Hope this should work. Before please confirm whether all the build settings for iOS configured properly or not.
Check platform :ios, '10.0' is uncommented
target 'CustomImageNotifications' do
  use_frameworks!
  pod 'Firebase/Analytics'
  pod 'Firebase/Messaging'
end 
flutter clean
rm -Rf ios/Pods
rm -Rf ios/.symlinks
rm -Rf ios/Flutter/Flutter.framework
rm -Rf ios/Flutter/Flutter.podspec
rm ios/Podfile
cd ios
flutter pub get
pod cache clean --all
pod install

    or  (below for m1 chip incase above command thrown error in pod install)

#1 Install ffi
sudo arch -x86_64 gem install ffi

#2 Re-install dependencies
arch -x86_64 pod install
1. Open ios/Pods/Pods.xcodeproj in Xcode
2. Change the iOS Deployment info from 8.0 to 9.0
From xcode clean / build again / run. Hope this should work. Before please confirm whether all the build settings for iOS configured properly or not.
Check platform :ios, '10.0' is uncommented
target 'CustomImageNotifications' do
  use_frameworks!
  pod 'Firebase/Analytics'
  pod 'Firebase/Messaging'
end 
% flutter clean

% cd ios
% arch -x86_64 pod update

Could not resolve com.google.guava:guava:30.1-jre - Gradle project sync failed. Basic functionality will not work properly - in kotlin project

copy iconCopydownload iconDownload
    repositories {
        mavenCentral()
        google()
    }

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        mavenCentral()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.1.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenCentral()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

.NET 6.0 not showing in Visual Studio 2022 (General Release)

copy iconCopydownload iconDownload
{
    "sdk": {
        "version": "6.0.100"
    }
}
dotnet tool install -g upgrade-assistant
cd "C:\your solution path"
upgrade-assistant analyze yourProject.csproj
cd "C:\your solution path"
upgrade-assistant upgrade yourProject.csproj
dotnet tool install -g upgrade-assistant
cd "C:\your solution path"
upgrade-assistant analyze yourProject.csproj
cd "C:\your solution path"
upgrade-assistant upgrade yourProject.csproj
dotnet tool install -g upgrade-assistant
cd "C:\your solution path"
upgrade-assistant analyze yourProject.csproj
cd "C:\your solution path"
upgrade-assistant upgrade yourProject.csproj

Ping Tasks will not complete

copy iconCopydownload iconDownload
    async Task Main()
    {
        var masterCts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); // 15s overall timeout
        
        var localMachines = new List<LocalMachine>
        {       
            new LocalMachine("192.0.0.1", false), // Should be not known - TimedOut
            new LocalMachine("192.168.86.88", false), // Should be not known - DestinationHostUnreachable (when timeout is 8000)
            new LocalMachine("www.dfdfsdfdfdsgrdf.cdcc", false), // Should be not known - status Unknown because of PingException
            new LocalMachine("192.168.86.87", false) // Known - my local IP
        };

        var results = new List<PingerResult>();

        try
        {
            // Create the "hot" tasks
            var tasks = localMachines.Where(m => !m.Online)
                                    .Select(m => new Pinger().SendPingAsync(m.HostOrAddress, 8000, masterCts.Token))
                                    .ToArray();

            await Task.WhenAll(tasks);
            
            results.AddRange(tasks.Select(t => t.Result));
        }
        finally
        {
            results.ForEach(r => localMachines.Single(m => m.HostOrAddress.Equals(r.HostOrAddress)).Online = r.Status == IPStatus.Success);

            results.Dump();  // For LINQPad
            localMachines.Dump(); // For LINQPad

            results.Clear();
        }
    }

    public class LocalMachine
    {
        public LocalMachine(string hostOrAddress, bool online)
        {
            HostOrAddress = hostOrAddress;
            Online = online;
        }

        public string HostOrAddress { get; }

        public bool Online { get; set; }
    }

    public class PingerResult
    {
        public string HostOrAddress {get;set;}
        
        public IPStatus Status {get;set;}
    }

    public class Pinger 
    {
        public async Task<PingerResult> SendPingAsync(string hostOrAddress, int timeout, CancellationToken token)
        {
            // Check if timeout has occurred
            token.ThrowIfCancellationRequested();

            IPStatus status = default;

            try
            {
                var reply = await SendPingInternal(hostOrAddress, timeout, token);
                status = reply.Status;
            }
            catch (PingException)
            {               
                status = IPStatus.Unknown;
            }
            
            return new PingerResult
            {
                HostOrAddress = hostOrAddress,
                Status = status
            };
        }

        // Wrap the legacy EAP pattern offered by Ping.
        private Task<PingReply> SendPingInternal(string hostOrAddress, int timeout, CancellationToken cancelToken)
        {
            var tcs = new TaskCompletionSource<PingReply>();

            if (cancelToken.IsCancellationRequested)
            {
                tcs.TrySetCanceled();
            }   
            else
            {
                using (var ping = new Ping())
                {
                    ping.PingCompleted += (object sender, PingCompletedEventArgs e) =>
                    {
                        if (!cancelToken.IsCancellationRequested)
                        {
                            if (e.Cancelled)
                            {
                                tcs.TrySetCanceled();
                            }
                            else if (e.Error != null)
                            {
                                tcs.TrySetException(e.Error);
                            }
                            else
                            {
                                tcs.TrySetResult(e.Reply);
                            }
                        }
                    };
                    
                    cancelToken.Register(() => { tcs.TrySetCanceled(); });

                    ping.SendAsync(hostOrAddress, timeout, new object());
                }
            };

            return tcs.Task;
        }
    }

How to hint at number *types* (i.e. subclasses of Number) - not numbers themselves?

copy iconCopydownload iconDownload
from typing import TypeVar
from decimal import Decimal
from fractions import Fraction

#: typevar of rational numbers if we squint real hard
Q = TypeVar("Q", float, Decimal, Fraction)
from typing import Type

def zero(t: Type[Q]) -> Q:
    return t()  # all Type[Q]s can be instantiated without arguments

print(zero(Fraction))
def one(t: Callable[[int], Q]) -> Q:
    return t(1)
from typing import TypeVar
from decimal import Decimal
from fractions import Fraction

#: typevar of rational numbers if we squint real hard
Q = TypeVar("Q", float, Decimal, Fraction)
from typing import Type

def zero(t: Type[Q]) -> Q:
    return t()  # all Type[Q]s can be instantiated without arguments

print(zero(Fraction))
def one(t: Callable[[int], Q]) -> Q:
    return t(1)
from typing import TypeVar
from decimal import Decimal
from fractions import Fraction

#: typevar of rational numbers if we squint real hard
Q = TypeVar("Q", float, Decimal, Fraction)
from typing import Type

def zero(t: Type[Q]) -> Q:
    return t()  # all Type[Q]s can be instantiated without arguments

print(zero(Fraction))
def one(t: Callable[[int], Q]) -> Q:
    return t(1)
def accepts_int_instances(x: int) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_instances(42) # passes MyPy (an instance of `int`)
accepts_int_instances(IntSubclass(666)) # passes MyPy (an instance of a subclass of `int`)
accepts_int_instances(3.14) # fails MyPy (an instance of `float` — `float` is not a subclass of `int`)
def accepts_int_and_subclasses(x: type[int]) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_and_subclasses(int) # passes MyPy 
accepts_int_and_subclasses(float) # fails Mypy (not a subclass of `int`)
accepts_int_and_subclasses(IntSubclass) # passes MyPy
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> issubclass(float, Number)
True
>>> from typeguard import typechecked
>>> from fractions import Fraction
>>> from decimal import Decimal
>>> import numpy as np
>>>
>>> @typechecked
... def foo(bar: type[Number]) -> None:
...     pass
... 
>>> foo(str)
Traceback (most recent call last):
TypeError: argument "bar" must be a subclass of numbers.Number; got str instead
>>> foo(int)
>>> foo(float)
>>> foo(complex)
>>> foo(Decimal)
>>> foo(Fraction)
>>> foo(np.int64)
>>> foo(np.float32)
>>> foo(np.ulonglong)
>>> # etc.
from numbers import Number
from fractions import Fraction
from decimal import Decimal


NumberType = type[Number]


def foo(bar: NumberType) -> None:
    pass


foo(float)  # fails 
foo(int)  # fails 
foo(Fraction)  # succeeds!
foo(Decimal)  # fails 
>>> # All classes have `object` in their mro
>>> class Foo: pass
>>> Foo.__mro__
(<class '__main__.Foo'>, <class 'object'>)
>>>
>>> # Subclasses of a class have that class in their mro
>>> class IntSubclass(int): pass
>>> IntSubclass.__mro__
(<class '__main__.IntSubclass'>, <class 'int'>, <class 'object'>)
>>> issubclass(IntSubclass, int)
True
>>>
>>> # But `Number` is not in the mro of `int`...
>>> int.__mro__
(<class 'int'>, <class 'object'>)
>>> # ...Yet `int` still pretends to be a subclass of `Number`!
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> #?!?!!??
from typing import SupportsFloat


NumberType = type[SupportsFloat]


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, Union 
from numbers import Number


NumberType = Union[type[SupportsFloat], type[complex], type[Number]]

# You can also write this more succinctly as:
# NumberType = type[Union[SupportsFloat, complex, Number]]
# The two are equivalent.

# In Python >= 3.10, we can even write it like this:
# NumberType = type[SupportsFloat | complex | Number]
# See PEP 604: https://www.python.org/dev/peps/pep-0604/


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, SupportsRound, Union
from numbers import Number

NumberType = Union[type[SupportsFloat], type[SupportsRound], type[complex], type[Number]]
def accepts_int_instances(x: int) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_instances(42) # passes MyPy (an instance of `int`)
accepts_int_instances(IntSubclass(666)) # passes MyPy (an instance of a subclass of `int`)
accepts_int_instances(3.14) # fails MyPy (an instance of `float` — `float` is not a subclass of `int`)
def accepts_int_and_subclasses(x: type[int]) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_and_subclasses(int) # passes MyPy 
accepts_int_and_subclasses(float) # fails Mypy (not a subclass of `int`)
accepts_int_and_subclasses(IntSubclass) # passes MyPy
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> issubclass(float, Number)
True
>>> from typeguard import typechecked
>>> from fractions import Fraction
>>> from decimal import Decimal
>>> import numpy as np
>>>
>>> @typechecked
... def foo(bar: type[Number]) -> None:
...     pass
... 
>>> foo(str)
Traceback (most recent call last):
TypeError: argument "bar" must be a subclass of numbers.Number; got str instead
>>> foo(int)
>>> foo(float)
>>> foo(complex)
>>> foo(Decimal)
>>> foo(Fraction)
>>> foo(np.int64)
>>> foo(np.float32)
>>> foo(np.ulonglong)
>>> # etc.
from numbers import Number
from fractions import Fraction
from decimal import Decimal


NumberType = type[Number]


def foo(bar: NumberType) -> None:
    pass


foo(float)  # fails 
foo(int)  # fails 
foo(Fraction)  # succeeds!
foo(Decimal)  # fails 
>>> # All classes have `object` in their mro
>>> class Foo: pass
>>> Foo.__mro__
(<class '__main__.Foo'>, <class 'object'>)
>>>
>>> # Subclasses of a class have that class in their mro
>>> class IntSubclass(int): pass
>>> IntSubclass.__mro__
(<class '__main__.IntSubclass'>, <class 'int'>, <class 'object'>)
>>> issubclass(IntSubclass, int)
True
>>>
>>> # But `Number` is not in the mro of `int`...
>>> int.__mro__
(<class 'int'>, <class 'object'>)
>>> # ...Yet `int` still pretends to be a subclass of `Number`!
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> #?!?!!??
from typing import SupportsFloat


NumberType = type[SupportsFloat]


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, Union 
from numbers import Number


NumberType = Union[type[SupportsFloat], type[complex], type[Number]]

# You can also write this more succinctly as:
# NumberType = type[Union[SupportsFloat, complex, Number]]
# The two are equivalent.

# In Python >= 3.10, we can even write it like this:
# NumberType = type[SupportsFloat | complex | Number]
# See PEP 604: https://www.python.org/dev/peps/pep-0604/


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, SupportsRound, Union
from numbers import Number

NumberType = Union[type[SupportsFloat], type[SupportsRound], type[complex], type[Number]]
def accepts_int_instances(x: int) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_instances(42) # passes MyPy (an instance of `int`)
accepts_int_instances(IntSubclass(666)) # passes MyPy (an instance of a subclass of `int`)
accepts_int_instances(3.14) # fails MyPy (an instance of `float` — `float` is not a subclass of `int`)
def accepts_int_and_subclasses(x: type[int]) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_and_subclasses(int) # passes MyPy 
accepts_int_and_subclasses(float) # fails Mypy (not a subclass of `int`)
accepts_int_and_subclasses(IntSubclass) # passes MyPy
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> issubclass(float, Number)
True
>>> from typeguard import typechecked
>>> from fractions import Fraction
>>> from decimal import Decimal
>>> import numpy as np
>>>
>>> @typechecked
... def foo(bar: type[Number]) -> None:
...     pass
... 
>>> foo(str)
Traceback (most recent call last):
TypeError: argument "bar" must be a subclass of numbers.Number; got str instead
>>> foo(int)
>>> foo(float)
>>> foo(complex)
>>> foo(Decimal)
>>> foo(Fraction)
>>> foo(np.int64)
>>> foo(np.float32)
>>> foo(np.ulonglong)
>>> # etc.
from numbers import Number
from fractions import Fraction
from decimal import Decimal


NumberType = type[Number]


def foo(bar: NumberType) -> None:
    pass


foo(float)  # fails 
foo(int)  # fails 
foo(Fraction)  # succeeds!
foo(Decimal)  # fails 
>>> # All classes have `object` in their mro
>>> class Foo: pass
>>> Foo.__mro__
(<class '__main__.Foo'>, <class 'object'>)
>>>
>>> # Subclasses of a class have that class in their mro
>>> class IntSubclass(int): pass
>>> IntSubclass.__mro__
(<class '__main__.IntSubclass'>, <class 'int'>, <class 'object'>)
>>> issubclass(IntSubclass, int)
True
>>>
>>> # But `Number` is not in the mro of `int`...
>>> int.__mro__
(<class 'int'>, <class 'object'>)
>>> # ...Yet `int` still pretends to be a subclass of `Number`!
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> #?!?!!??
from typing import SupportsFloat


NumberType = type[SupportsFloat]


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, Union 
from numbers import Number


NumberType = Union[type[SupportsFloat], type[complex], type[Number]]

# You can also write this more succinctly as:
# NumberType = type[Union[SupportsFloat, complex, Number]]
# The two are equivalent.

# In Python >= 3.10, we can even write it like this:
# NumberType = type[SupportsFloat | complex | Number]
# See PEP 604: https://www.python.org/dev/peps/pep-0604/


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, SupportsRound, Union
from numbers import Number

NumberType = Union[type[SupportsFloat], type[SupportsRound], type[complex], type[Number]]
def accepts_int_instances(x: int) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_instances(42) # passes MyPy (an instance of `int`)
accepts_int_instances(IntSubclass(666)) # passes MyPy (an instance of a subclass of `int`)
accepts_int_instances(3.14) # fails MyPy (an instance of `float` — `float` is not a subclass of `int`)
def accepts_int_and_subclasses(x: type[int]) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_and_subclasses(int) # passes MyPy 
accepts_int_and_subclasses(float) # fails Mypy (not a subclass of `int`)
accepts_int_and_subclasses(IntSubclass) # passes MyPy
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> issubclass(float, Number)
True
>>> from typeguard import typechecked
>>> from fractions import Fraction
>>> from decimal import Decimal
>>> import numpy as np
>>>
>>> @typechecked
... def foo(bar: type[Number]) -> None:
...     pass
... 
>>> foo(str)
Traceback (most recent call last):
TypeError: argument "bar" must be a subclass of numbers.Number; got str instead
>>> foo(int)
>>> foo(float)
>>> foo(complex)
>>> foo(Decimal)
>>> foo(Fraction)
>>> foo(np.int64)
>>> foo(np.float32)
>>> foo(np.ulonglong)
>>> # etc.
from numbers import Number
from fractions import Fraction
from decimal import Decimal


NumberType = type[Number]


def foo(bar: NumberType) -> None:
    pass


foo(float)  # fails 
foo(int)  # fails 
foo(Fraction)  # succeeds!
foo(Decimal)  # fails 
>>> # All classes have `object` in their mro
>>> class Foo: pass
>>> Foo.__mro__
(<class '__main__.Foo'>, <class 'object'>)
>>>
>>> # Subclasses of a class have that class in their mro
>>> class IntSubclass(int): pass
>>> IntSubclass.__mro__
(<class '__main__.IntSubclass'>, <class 'int'>, <class 'object'>)
>>> issubclass(IntSubclass, int)
True
>>>
>>> # But `Number` is not in the mro of `int`...
>>> int.__mro__
(<class 'int'>, <class 'object'>)
>>> # ...Yet `int` still pretends to be a subclass of `Number`!
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> #?!?!!??
from typing import SupportsFloat


NumberType = type[SupportsFloat]


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, Union 
from numbers import Number


NumberType = Union[type[SupportsFloat], type[complex], type[Number]]

# You can also write this more succinctly as:
# NumberType = type[Union[SupportsFloat, complex, Number]]
# The two are equivalent.

# In Python >= 3.10, we can even write it like this:
# NumberType = type[SupportsFloat | complex | Number]
# See PEP 604: https://www.python.org/dev/peps/pep-0604/


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, SupportsRound, Union
from numbers import Number

NumberType = Union[type[SupportsFloat], type[SupportsRound], type[complex], type[Number]]
def accepts_int_instances(x: int) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_instances(42) # passes MyPy (an instance of `int`)
accepts_int_instances(IntSubclass(666)) # passes MyPy (an instance of a subclass of `int`)
accepts_int_instances(3.14) # fails MyPy (an instance of `float` — `float` is not a subclass of `int`)
def accepts_int_and_subclasses(x: type[int]) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_and_subclasses(int) # passes MyPy 
accepts_int_and_subclasses(float) # fails Mypy (not a subclass of `int`)
accepts_int_and_subclasses(IntSubclass) # passes MyPy
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> issubclass(float, Number)
True
>>> from typeguard import typechecked
>>> from fractions import Fraction
>>> from decimal import Decimal
>>> import numpy as np
>>>
>>> @typechecked
... def foo(bar: type[Number]) -> None:
...     pass
... 
>>> foo(str)
Traceback (most recent call last):
TypeError: argument "bar" must be a subclass of numbers.Number; got str instead
>>> foo(int)
>>> foo(float)
>>> foo(complex)
>>> foo(Decimal)
>>> foo(Fraction)
>>> foo(np.int64)
>>> foo(np.float32)
>>> foo(np.ulonglong)
>>> # etc.
from numbers import Number
from fractions import Fraction
from decimal import Decimal


NumberType = type[Number]


def foo(bar: NumberType) -> None:
    pass


foo(float)  # fails 
foo(int)  # fails 
foo(Fraction)  # succeeds!
foo(Decimal)  # fails 
>>> # All classes have `object` in their mro
>>> class Foo: pass
>>> Foo.__mro__
(<class '__main__.Foo'>, <class 'object'>)
>>>
>>> # Subclasses of a class have that class in their mro
>>> class IntSubclass(int): pass
>>> IntSubclass.__mro__
(<class '__main__.IntSubclass'>, <class 'int'>, <class 'object'>)
>>> issubclass(IntSubclass, int)
True
>>>
>>> # But `Number` is not in the mro of `int`...
>>> int.__mro__
(<class 'int'>, <class 'object'>)
>>> # ...Yet `int` still pretends to be a subclass of `Number`!
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> #?!?!!??
from typing import SupportsFloat


NumberType = type[SupportsFloat]


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, Union 
from numbers import Number


NumberType = Union[type[SupportsFloat], type[complex], type[Number]]

# You can also write this more succinctly as:
# NumberType = type[Union[SupportsFloat, complex, Number]]
# The two are equivalent.

# In Python >= 3.10, we can even write it like this:
# NumberType = type[SupportsFloat | complex | Number]
# See PEP 604: https://www.python.org/dev/peps/pep-0604/


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, SupportsRound, Union
from numbers import Number

NumberType = Union[type[SupportsFloat], type[SupportsRound], type[complex], type[Number]]
def accepts_int_instances(x: int) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_instances(42) # passes MyPy (an instance of `int`)
accepts_int_instances(IntSubclass(666)) # passes MyPy (an instance of a subclass of `int`)
accepts_int_instances(3.14) # fails MyPy (an instance of `float` — `float` is not a subclass of `int`)
def accepts_int_and_subclasses(x: type[int]) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_and_subclasses(int) # passes MyPy 
accepts_int_and_subclasses(float) # fails Mypy (not a subclass of `int`)
accepts_int_and_subclasses(IntSubclass) # passes MyPy
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> issubclass(float, Number)
True
>>> from typeguard import typechecked
>>> from fractions import Fraction
>>> from decimal import Decimal
>>> import numpy as np
>>>
>>> @typechecked
... def foo(bar: type[Number]) -> None:
...     pass
... 
>>> foo(str)
Traceback (most recent call last):
TypeError: argument "bar" must be a subclass of numbers.Number; got str instead
>>> foo(int)
>>> foo(float)
>>> foo(complex)
>>> foo(Decimal)
>>> foo(Fraction)
>>> foo(np.int64)
>>> foo(np.float32)
>>> foo(np.ulonglong)
>>> # etc.
from numbers import Number
from fractions import Fraction
from decimal import Decimal


NumberType = type[Number]


def foo(bar: NumberType) -> None:
    pass


foo(float)  # fails 
foo(int)  # fails 
foo(Fraction)  # succeeds!
foo(Decimal)  # fails 
>>> # All classes have `object` in their mro
>>> class Foo: pass
>>> Foo.__mro__
(<class '__main__.Foo'>, <class 'object'>)
>>>
>>> # Subclasses of a class have that class in their mro
>>> class IntSubclass(int): pass
>>> IntSubclass.__mro__
(<class '__main__.IntSubclass'>, <class 'int'>, <class 'object'>)
>>> issubclass(IntSubclass, int)
True
>>>
>>> # But `Number` is not in the mro of `int`...
>>> int.__mro__
(<class 'int'>, <class 'object'>)
>>> # ...Yet `int` still pretends to be a subclass of `Number`!
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> #?!?!!??
from typing import SupportsFloat


NumberType = type[SupportsFloat]


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, Union 
from numbers import Number


NumberType = Union[type[SupportsFloat], type[complex], type[Number]]

# You can also write this more succinctly as:
# NumberType = type[Union[SupportsFloat, complex, Number]]
# The two are equivalent.

# In Python >= 3.10, we can even write it like this:
# NumberType = type[SupportsFloat | complex | Number]
# See PEP 604: https://www.python.org/dev/peps/pep-0604/


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, SupportsRound, Union
from numbers import Number

NumberType = Union[type[SupportsFloat], type[SupportsRound], type[complex], type[Number]]
def accepts_int_instances(x: int) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_instances(42) # passes MyPy (an instance of `int`)
accepts_int_instances(IntSubclass(666)) # passes MyPy (an instance of a subclass of `int`)
accepts_int_instances(3.14) # fails MyPy (an instance of `float` — `float` is not a subclass of `int`)
def accepts_int_and_subclasses(x: type[int]) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_and_subclasses(int) # passes MyPy 
accepts_int_and_subclasses(float) # fails Mypy (not a subclass of `int`)
accepts_int_and_subclasses(IntSubclass) # passes MyPy
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> issubclass(float, Number)
True
>>> from typeguard import typechecked
>>> from fractions import Fraction
>>> from decimal import Decimal
>>> import numpy as np
>>>
>>> @typechecked
... def foo(bar: type[Number]) -> None:
...     pass
... 
>>> foo(str)
Traceback (most recent call last):
TypeError: argument "bar" must be a subclass of numbers.Number; got str instead
>>> foo(int)
>>> foo(float)
>>> foo(complex)
>>> foo(Decimal)
>>> foo(Fraction)
>>> foo(np.int64)
>>> foo(np.float32)
>>> foo(np.ulonglong)
>>> # etc.
from numbers import Number
from fractions import Fraction
from decimal import Decimal


NumberType = type[Number]


def foo(bar: NumberType) -> None:
    pass


foo(float)  # fails 
foo(int)  # fails 
foo(Fraction)  # succeeds!
foo(Decimal)  # fails 
>>> # All classes have `object` in their mro
>>> class Foo: pass
>>> Foo.__mro__
(<class '__main__.Foo'>, <class 'object'>)
>>>
>>> # Subclasses of a class have that class in their mro
>>> class IntSubclass(int): pass
>>> IntSubclass.__mro__
(<class '__main__.IntSubclass'>, <class 'int'>, <class 'object'>)
>>> issubclass(IntSubclass, int)
True
>>>
>>> # But `Number` is not in the mro of `int`...
>>> int.__mro__
(<class 'int'>, <class 'object'>)
>>> # ...Yet `int` still pretends to be a subclass of `Number`!
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> #?!?!!??
from typing import SupportsFloat


NumberType = type[SupportsFloat]


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, Union 
from numbers import Number


NumberType = Union[type[SupportsFloat], type[complex], type[Number]]

# You can also write this more succinctly as:
# NumberType = type[Union[SupportsFloat, complex, Number]]
# The two are equivalent.

# In Python >= 3.10, we can even write it like this:
# NumberType = type[SupportsFloat | complex | Number]
# See PEP 604: https://www.python.org/dev/peps/pep-0604/


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, SupportsRound, Union
from numbers import Number

NumberType = Union[type[SupportsFloat], type[SupportsRound], type[complex], type[Number]]
def accepts_int_instances(x: int) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_instances(42) # passes MyPy (an instance of `int`)
accepts_int_instances(IntSubclass(666)) # passes MyPy (an instance of a subclass of `int`)
accepts_int_instances(3.14) # fails MyPy (an instance of `float` — `float` is not a subclass of `int`)
def accepts_int_and_subclasses(x: type[int]) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_and_subclasses(int) # passes MyPy 
accepts_int_and_subclasses(float) # fails Mypy (not a subclass of `int`)
accepts_int_and_subclasses(IntSubclass) # passes MyPy
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> issubclass(float, Number)
True
>>> from typeguard import typechecked
>>> from fractions import Fraction
>>> from decimal import Decimal
>>> import numpy as np
>>>
>>> @typechecked
... def foo(bar: type[Number]) -> None:
...     pass
... 
>>> foo(str)
Traceback (most recent call last):
TypeError: argument "bar" must be a subclass of numbers.Number; got str instead
>>> foo(int)
>>> foo(float)
>>> foo(complex)
>>> foo(Decimal)
>>> foo(Fraction)
>>> foo(np.int64)
>>> foo(np.float32)
>>> foo(np.ulonglong)
>>> # etc.
from numbers import Number
from fractions import Fraction
from decimal import Decimal


NumberType = type[Number]


def foo(bar: NumberType) -> None:
    pass


foo(float)  # fails 
foo(int)  # fails 
foo(Fraction)  # succeeds!
foo(Decimal)  # fails 
>>> # All classes have `object` in their mro
>>> class Foo: pass
>>> Foo.__mro__
(<class '__main__.Foo'>, <class 'object'>)
>>>
>>> # Subclasses of a class have that class in their mro
>>> class IntSubclass(int): pass
>>> IntSubclass.__mro__
(<class '__main__.IntSubclass'>, <class 'int'>, <class 'object'>)
>>> issubclass(IntSubclass, int)
True
>>>
>>> # But `Number` is not in the mro of `int`...
>>> int.__mro__
(<class 'int'>, <class 'object'>)
>>> # ...Yet `int` still pretends to be a subclass of `Number`!
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> #?!?!!??
from typing import SupportsFloat


NumberType = type[SupportsFloat]


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, Union 
from numbers import Number


NumberType = Union[type[SupportsFloat], type[complex], type[Number]]

# You can also write this more succinctly as:
# NumberType = type[Union[SupportsFloat, complex, Number]]
# The two are equivalent.

# In Python >= 3.10, we can even write it like this:
# NumberType = type[SupportsFloat | complex | Number]
# See PEP 604: https://www.python.org/dev/peps/pep-0604/


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, SupportsRound, Union
from numbers import Number

NumberType = Union[type[SupportsFloat], type[SupportsRound], type[complex], type[Number]]
def accepts_int_instances(x: int) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_instances(42) # passes MyPy (an instance of `int`)
accepts_int_instances(IntSubclass(666)) # passes MyPy (an instance of a subclass of `int`)
accepts_int_instances(3.14) # fails MyPy (an instance of `float` — `float` is not a subclass of `int`)
def accepts_int_and_subclasses(x: type[int]) -> None:
    pass


class IntSubclass(int):
    pass


accepts_int_and_subclasses(int) # passes MyPy 
accepts_int_and_subclasses(float) # fails Mypy (not a subclass of `int`)
accepts_int_and_subclasses(IntSubclass) # passes MyPy
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> issubclass(float, Number)
True
>>> from typeguard import typechecked
>>> from fractions import Fraction
>>> from decimal import Decimal
>>> import numpy as np
>>>
>>> @typechecked
... def foo(bar: type[Number]) -> None:
...     pass
... 
>>> foo(str)
Traceback (most recent call last):
TypeError: argument "bar" must be a subclass of numbers.Number; got str instead
>>> foo(int)
>>> foo(float)
>>> foo(complex)
>>> foo(Decimal)
>>> foo(Fraction)
>>> foo(np.int64)
>>> foo(np.float32)
>>> foo(np.ulonglong)
>>> # etc.
from numbers import Number
from fractions import Fraction
from decimal import Decimal


NumberType = type[Number]


def foo(bar: NumberType) -> None:
    pass


foo(float)  # fails 
foo(int)  # fails 
foo(Fraction)  # succeeds!
foo(Decimal)  # fails 
>>> # All classes have `object` in their mro
>>> class Foo: pass
>>> Foo.__mro__
(<class '__main__.Foo'>, <class 'object'>)
>>>
>>> # Subclasses of a class have that class in their mro
>>> class IntSubclass(int): pass
>>> IntSubclass.__mro__
(<class '__main__.IntSubclass'>, <class 'int'>, <class 'object'>)
>>> issubclass(IntSubclass, int)
True
>>>
>>> # But `Number` is not in the mro of `int`...
>>> int.__mro__
(<class 'int'>, <class 'object'>)
>>> # ...Yet `int` still pretends to be a subclass of `Number`!
>>> from numbers import Number 
>>> issubclass(int, Number)
True
>>> #?!?!!??
from typing import SupportsFloat


NumberType = type[SupportsFloat]


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, Union 
from numbers import Number


NumberType = Union[type[SupportsFloat], type[complex], type[Number]]

# You can also write this more succinctly as:
# NumberType = type[Union[SupportsFloat, complex, Number]]
# The two are equivalent.

# In Python >= 3.10, we can even write it like this:
# NumberType = type[SupportsFloat | complex | Number]
# See PEP 604: https://www.python.org/dev/peps/pep-0604/


def foo(bar: NumberType) -> None:
    pass
from typing import SupportsFloat, SupportsRound, Union
from numbers import Number

NumberType = Union[type[SupportsFloat], type[SupportsRound], type[complex], type[Number]]

How can I dynamically pick a member from two similar C++ structures while avoiding code duplication?

copy iconCopydownload iconDownload
#define CAST_IF(N, XY) if (x == N) reinterpret_cast<XY*>(object)

#define ASSIGN(FIELD, VALUE) \
    do { \
        CAST_IF(1, XY)->FIELD = VALUE; \
        else CAST_IF(2, XYZ)->FIELD = VALUE; \
    } while (false)
int *ptest;

switch (x) {
    case 1: ptest = &(static_cast<XY*>(object)->test); break;
    case 2: ptest = &(static_cast<XYZ*>(object)->test); break;
    ...
}

*ptest = 1;
const std:unordered_map<int, size_t> offsets = {
    {1, offsetof(XY, test)},
    {2, offsetof(XYZ, test)}
    ...
};

...

*reinterpret_cast<int*>(static_cast<char*>(object) + offsets[x]) = 1;
int *ptest;

switch (x) {
    case 1: ptest = &(static_cast<XY*>(object)->test); break;
    case 2: ptest = &(static_cast<XYZ*>(object)->test); break;
    ...
}

*ptest = 1;
const std:unordered_map<int, size_t> offsets = {
    {1, offsetof(XY, test)},
    {2, offsetof(XYZ, test)}
    ...
};

...

*reinterpret_cast<int*>(static_cast<char*>(object) + offsets[x]) = 1;
#define FlexibleOffset(class1, class2, member) (x == 1 ? offsetof(class1, member) : offsetof(class2, member))
#define FlexibleMember(object, member) *reinterpret_cast<decltype(XY::member)*>(reinterpret_cast<uintptr_t>(object) + FlexibleOffset(XY, XYZ, member))

FlexibleMember(object, test) = 1;
void* addressTo = &FlexibleMember(object, test);
struct XYZWrapper
{
    XYZWrapper(void* ptr)
    {
        if (x == 1)
        {
            extra = nullptr; // doesn't exist in x == 1
            test = reinterpret_cast<XY*>(ptr)->test;
        }
        else if (x == 2)
        {
            extra = reinterpret_cast<XYZ*>(ptr)->extra;
            test = reinterpret_cast<XYZ*>(ptr)->test;
        }
    }
    XYZWrapper* operator->() { return this; }
    short* extra;
    int* test;
}

*XYZWrapper(object)->test = 1;
void* addressTo = XYZWrapper(object)->test;

void SomeFunction(XYZWrapper object)
{
    *object->test = 1;
    if (x == 2) *object->extra = 4;
}
#define FlexibleOffset(class1, class2, member) (x == 1 ? offsetof(class1, member) : offsetof(class2, member))
#define FlexibleMember(object, member) *reinterpret_cast<decltype(XY::member)*>(reinterpret_cast<uintptr_t>(object) + FlexibleOffset(XY, XYZ, member))

FlexibleMember(object, test) = 1;
void* addressTo = &FlexibleMember(object, test);
struct XYZWrapper
{
    XYZWrapper(void* ptr)
    {
        if (x == 1)
        {
            extra = nullptr; // doesn't exist in x == 1
            test = reinterpret_cast<XY*>(ptr)->test;
        }
        else if (x == 2)
        {
            extra = reinterpret_cast<XYZ*>(ptr)->extra;
            test = reinterpret_cast<XYZ*>(ptr)->test;
        }
    }
    XYZWrapper* operator->() { return this; }
    short* extra;
    int* test;
}

*XYZWrapper(object)->test = 1;
void* addressTo = XYZWrapper(object)->test;

void SomeFunction(XYZWrapper object)
{
    *object->test = 1;
    if (x == 2) *object->extra = 4;
}
pick_cast<XY,XYZ>(x==2)(object)->*test = 3;
using vptr_t= std::variant<XY*, XYZ*>;
void foo(vptr_t ptr){
  std::visit([&](auto*ptr){ptr->test=3;}, ptr);
}
vptr_t get_vptr_from_void(int x, void*p){
  switch(x){
    case 1: return reinterpret_cast<XY*>(p);
    case 2: return reinterpret_cast<XYZ*>(p);
  }
}
pick_cast<XY,XYZ>(x==2)(object)->*test = 3;
using vptr_t= std::variant<XY*, XYZ*>;
void foo(vptr_t ptr){
  std::visit([&](auto*ptr){ptr->test=3;}, ptr);
}
vptr_t get_vptr_from_void(int x, void*p){
  switch(x){
    case 1: return reinterpret_cast<XY*>(p);
    case 2: return reinterpret_cast<XYZ*>(p);
  }
}
pick_cast<XY,XYZ>(x==2)(object)->*test = 3;
using vptr_t= std::variant<XY*, XYZ*>;
void foo(vptr_t ptr){
  std::visit([&](auto*ptr){ptr->test=3;}, ptr);
}
vptr_t get_vptr_from_void(int x, void*p){
  switch(x){
    case 1: return reinterpret_cast<XY*>(p);
    case 2: return reinterpret_cast<XYZ*>(p);
  }
}
#include <array>

struct XY { int test; };

struct XYZ {
  short extra;
  int test;
};

template<class... Objects>
constexpr std::array table = {
  +[](void* object) { reinterpret_cast<Objects*>(object)->test = 1; }...
};

void Function(void* object, int index) {
  // Register your class
  const auto& dispatches = table<XY, XYZ>;
  dispatches[index](object);
}
class XY_base{
public:
   virtual int& Test() = 0;
};

class XY : public XY_base
{
    int test;
public:
    int& Test() override{return test;}
};

class XYZ : public XY_base
{
    short extra;
    int test;
public:
    int& Test() override{return test;}
};
void Function(XY_base* object)
{
    object->Test() = 1;  // no IF ELSE
}
class XY_base{
public:
   virtual int& Test() = 0;
};

class XY : public XY_base
{
    int test;
public:
    int& Test() override{return test;}
};

class XYZ : public XY_base
{
    short extra;
    int test;
public:
    int& Test() override{return test;}
};
void Function(XY_base* object)
{
    object->Test() = 1;  // no IF ELSE
}
#include <memory>

struct Car
{
    std::string model;
    int numWheels;
};

struct Truck
{
    int weight;
    int numWheels;
    std::string model;
};

struct BaseVehicleWrapper
{
    virtual void setNumberWheels(int value) = 0;
    virtual void setModel(const std::string& model) = 0;
};

template <typename T>
struct VehicleWrapper : public BaseVehicleWrapper
{
    T& m_obj;
    VehicleWrapper(T& obj) : m_obj(obj) { }
    void setNumberWheels(int value) override { m_obj.numWheels = value; }
    void setModel(const std::string& model) override { m_obj.model = model; }
};

template <typename T>
std::unique_ptr<BaseVehicleWrapper> CreateVehicleWrapper(T& obj)
{
    return std::make_unique<VehicleWrapper<T>>(obj);
}
Car car;
Truck truck;

bool selectCar = true;

auto selectedVehicle = selectCar ? CreateVehicleWrapper(car) : CreateVehicleWrapper(truck);

selectedVehicle->setNumberWheels(4);
selectedVehicle->setModel("Beetle");
void Function(void* object)
{
    if (x == 1)
    {
        reinterpret_cast<XY*> (object)->test = 1;
    }
    else if (x == 2)
    {
        reinterpret_cast<XYZ*> (object)->test = 1;
    }
}
void Function() override
{
    m_obj.test = 1;
}
#include <memory>

struct Car
{
    std::string model;
    int numWheels;
};

struct Truck
{
    int weight;
    int numWheels;
    std::string model;
};

struct BaseVehicleWrapper
{
    virtual void setNumberWheels(int value) = 0;
    virtual void setModel(const std::string& model) = 0;
};

template <typename T>
struct VehicleWrapper : public BaseVehicleWrapper
{
    T& m_obj;
    VehicleWrapper(T& obj) : m_obj(obj) { }
    void setNumberWheels(int value) override { m_obj.numWheels = value; }
    void setModel(const std::string& model) override { m_obj.model = model; }
};

template <typename T>
std::unique_ptr<BaseVehicleWrapper> CreateVehicleWrapper(T& obj)
{
    return std::make_unique<VehicleWrapper<T>>(obj);
}
Car car;
Truck truck;

bool selectCar = true;

auto selectedVehicle = selectCar ? CreateVehicleWrapper(car) : CreateVehicleWrapper(truck);

selectedVehicle->setNumberWheels(4);
selectedVehicle->setModel("Beetle");
void Function(void* object)
{
    if (x == 1)
    {
        reinterpret_cast<XY*> (object)->test = 1;
    }
    else if (x == 2)
    {
        reinterpret_cast<XYZ*> (object)->test = 1;
    }
}
void Function() override
{
    m_obj.test = 1;
}
#include <memory>

struct Car
{
    std::string model;
    int numWheels;
};

struct Truck
{
    int weight;
    int numWheels;
    std::string model;
};

struct BaseVehicleWrapper
{
    virtual void setNumberWheels(int value) = 0;
    virtual void setModel(const std::string& model) = 0;
};

template <typename T>
struct VehicleWrapper : public BaseVehicleWrapper
{
    T& m_obj;
    VehicleWrapper(T& obj) : m_obj(obj) { }
    void setNumberWheels(int value) override { m_obj.numWheels = value; }
    void setModel(const std::string& model) override { m_obj.model = model; }
};

template <typename T>
std::unique_ptr<BaseVehicleWrapper> CreateVehicleWrapper(T& obj)
{
    return std::make_unique<VehicleWrapper<T>>(obj);
}
Car car;
Truck truck;

bool selectCar = true;

auto selectedVehicle = selectCar ? CreateVehicleWrapper(car) : CreateVehicleWrapper(truck);

selectedVehicle->setNumberWheels(4);
selectedVehicle->setModel("Beetle");
void Function(void* object)
{
    if (x == 1)
    {
        reinterpret_cast<XY*> (object)->test = 1;
    }
    else if (x == 2)
    {
        reinterpret_cast<XYZ*> (object)->test = 1;
    }
}
void Function() override
{
    m_obj.test = 1;
}
#include <memory>

struct Car
{
    std::string model;
    int numWheels;
};

struct Truck
{
    int weight;
    int numWheels;
    std::string model;
};

struct BaseVehicleWrapper
{
    virtual void setNumberWheels(int value) = 0;
    virtual void setModel(const std::string& model) = 0;
};

template <typename T>
struct VehicleWrapper : public BaseVehicleWrapper
{
    T& m_obj;
    VehicleWrapper(T& obj) : m_obj(obj) { }
    void setNumberWheels(int value) override { m_obj.numWheels = value; }
    void setModel(const std::string& model) override { m_obj.model = model; }
};

template <typename T>
std::unique_ptr<BaseVehicleWrapper> CreateVehicleWrapper(T& obj)
{
    return std::make_unique<VehicleWrapper<T>>(obj);
}
Car car;
Truck truck;

bool selectCar = true;

auto selectedVehicle = selectCar ? CreateVehicleWrapper(car) : CreateVehicleWrapper(truck);

selectedVehicle->setNumberWheels(4);
selectedVehicle->setModel("Beetle");
void Function(void* object)
{
    if (x == 1)
    {
        reinterpret_cast<XY*> (object)->test = 1;
    }
    else if (x == 2)
    {
        reinterpret_cast<XYZ*> (object)->test = 1;
    }
}
void Function() override
{
    m_obj.test = 1;
}
#include <cstdlib>

template <typename F>
inline static auto dispatch(int x, void *ptr, F perform) -> auto
{
    if (x == 1)
        return perform(reinterpret_cast<XY *>(ptr));
    if (x == 2)
        return perform(reinterpret_cast<XYZ *>(ptr));
    std::abort();
}

void Function(void* object)
{
    dispatch(x, object, [] (auto ptr) {
        ptr->test = 1;
    });
}
#include <ranges>

template <int i>
struct types {};

template <>
struct types<1>
{ typedef XY type; };

template <>
struct types<2>
{ typedef XYZ type; };

void Function(void* object)
{
    template for (constexpr int i : std::views::iota(1, 3)) {
        if (x == i) {
            reinterpret_cast<typename types<i>::type *>(object)->test = 1;
        }
    }
}
#include <cstdlib>

template <typename F>
inline static auto dispatch(int x, void *ptr, F perform) -> auto
{
    if (x == 1)
        return perform(reinterpret_cast<XY *>(ptr));
    if (x == 2)
        return perform(reinterpret_cast<XYZ *>(ptr));
    std::abort();
}

void Function(void* object)
{
    dispatch(x, object, [] (auto ptr) {
        ptr->test = 1;
    });
}
#include <ranges>

template <int i>
struct types {};

template <>
struct types<1>
{ typedef XY type; };

template <>
struct types<2>
{ typedef XYZ type; };

void Function(void* object)
{
    template for (constexpr int i : std::views::iota(1, 3)) {
        if (x == i) {
            reinterpret_cast<typename types<i>::type *>(object)->test = 1;
        }
    }
}

What's a good way to store a small, fixed size, hierarchical set of static data?

copy iconCopydownload iconDownload
struct MidiEventType
{
    char value;
    char byteRequired; // Store the number of bytes required to be read
};

struct MidiEventTypes{
   static constexpr MidiEventType NOTE_OFF { 8, 2};
   static constexpr MidiEventType NOTE_ON { 9, 2};
   static constexpr MidiEventType KEY_AFTERTOUCH { 10, 2};
   static constexpr MidiEventType CONTROL_CHANGE { 11, 2};
   static constexpr MidiEventType PROGRAM_CHANGE  { 12, 1};
   static constexpr MidiEventType CHANNEL_AFTERTOUCH { 13, 1};
   static constexpr MidiEventType PITCH_WHEEL_CHANGE { 14, 2};
};
#include <array>
#include <cstddef>
#include <stdexcept>
#include <iostream>

enum class MidiEvents {
   NOTE_OFF,
   NOTE_ON,
   KEY_AFTERTOUCH,
   CONTROL_CHANGE,
   PROGRAM_CHANGE,
   CHANNEL_AFTERTOUCH,
   PITCH_WHEEL_CHANGE,
   MIDIEVENTS_CNT,
};
constexpr bool operator==(const MidiEvents& a, const char& b) {
    return b == static_cast<char>(a);
}

struct MidiEventType {
    char value;
    char num_bytes; // Store the number of bytes required to be read
    constexpr bool operator==(const char& other) const {
        return value == other;        
    }
    constexpr bool operator==(const MidiEvents& other) const {
        return static_cast<char>(other) == value;
    }
};
constexpr bool operator==(const char& a, const MidiEventType& b) {
    return b == a;
}

struct MidiEventTypes {
    static constexpr std::array<
        MidiEventType, static_cast<size_t>(MidiEvents::MIDIEVENTS_CNT)
    > _data{{
        [static_cast<char>(MidiEvents::NOTE_OFF)] = {8, 2},
        [static_cast<char>(MidiEvents::NOTE_ON)] = {9, 2},
        /* etc.... */
    }};
    static constexpr auto get(char m) {
        for (auto&& i : _data) {
            if (i.value == m) {
                return i;
            }
        }
    }
    static constexpr auto get(MidiEvents m) {
        return _data[static_cast<char>(m)];
    }
    static constexpr auto GetRequiredBytesByEventType(char m) {
        return get(m).num_bytes;
    }
    static constexpr auto GetRequiredBytesByEventType(MidiEvents m) {
        return get(m).num_bytes;
    }
    static constexpr auto NOTE_OFF = _data[static_cast<char>(MidiEvents::NOTE_OFF)];
    static constexpr auto NOTE_ON = _data[static_cast<char>(MidiEvents::NOTE_ON)];
};
int main() {
    // Here's some pseudo code usage:
    constexpr char nTestValue = 8;
    if (nTestValue == MidiEventTypes::NOTE_OFF) {
        std::cout << "We now need to read " << MidiEventTypes::NOTE_OFF.num_bytes << " more bytes...." << std::endl;
    }
    // We should also be able to do something like this:
    // Get the number of read bytes required for a MIDI event with a type equal to the value of nTestValue.
    constexpr char nBytesNeeded = MidiEventTypes::get(nTestValue).num_bytes; 
    // Or alternatively:
    constexpr char nBytesNeeded2 = MidiEventTypes::GetRequiredBytesByEventType(nTestValue);
    // and:
    constexpr char nBytesNeeded3 = MidiEventTypes::GetRequiredBytesByEventType(MidiEvents::NOTE_OFF);
}
#include <array>
#include <cstddef>
#include <stdexcept>
#include <iostream>

enum class MidiEvents {
   NOTE_OFF,
   NOTE_ON,
   KEY_AFTERTOUCH,
   CONTROL_CHANGE,
   PROGRAM_CHANGE,
   CHANNEL_AFTERTOUCH,
   PITCH_WHEEL_CHANGE,
   MIDIEVENTS_CNT,
};
constexpr bool operator==(const MidiEvents& a, const char& b) {
    return b == static_cast<char>(a);
}

struct MidiEventType {
    char value;
    char num_bytes; // Store the number of bytes required to be read
    constexpr bool operator==(const char& other) const {
        return value == other;        
    }
    constexpr bool operator==(const MidiEvents& other) const {
        return static_cast<char>(other) == value;
    }
};
constexpr bool operator==(const char& a, const MidiEventType& b) {
    return b == a;
}

struct MidiEventTypes {
    static constexpr std::array<
        MidiEventType, static_cast<size_t>(MidiEvents::MIDIEVENTS_CNT)
    > _data{{
        [static_cast<char>(MidiEvents::NOTE_OFF)] = {8, 2},
        [static_cast<char>(MidiEvents::NOTE_ON)] = {9, 2},
        /* etc.... */
    }};
    static constexpr auto get(char m) {
        for (auto&& i : _data) {
            if (i.value == m) {
                return i;
            }
        }
    }
    static constexpr auto get(MidiEvents m) {
        return _data[static_cast<char>(m)];
    }
    static constexpr auto GetRequiredBytesByEventType(char m) {
        return get(m).num_bytes;
    }
    static constexpr auto GetRequiredBytesByEventType(MidiEvents m) {
        return get(m).num_bytes;
    }
    static constexpr auto NOTE_OFF = _data[static_cast<char>(MidiEvents::NOTE_OFF)];
    static constexpr auto NOTE_ON = _data[static_cast<char>(MidiEvents::NOTE_ON)];
};
int main() {
    // Here's some pseudo code usage:
    constexpr char nTestValue = 8;
    if (nTestValue == MidiEventTypes::NOTE_OFF) {
        std::cout << "We now need to read " << MidiEventTypes::NOTE_OFF.num_bytes << " more bytes...." << std::endl;
    }
    // We should also be able to do something like this:
    // Get the number of read bytes required for a MIDI event with a type equal to the value of nTestValue.
    constexpr char nBytesNeeded = MidiEventTypes::get(nTestValue).num_bytes; 
    // Or alternatively:
    constexpr char nBytesNeeded2 = MidiEventTypes::GetRequiredBytesByEventType(nTestValue);
    // and:
    constexpr char nBytesNeeded3 = MidiEventTypes::GetRequiredBytesByEventType(MidiEvents::NOTE_OFF);
}
#include <iostream>

template <int V, int B>
struct MidiEventType
{
    static constexpr int value = V;

    static constexpr int bytes = B;

    constexpr operator int() const
    {
        return V;
    }
};

// dummy classes, used for accessing a given property from MidiEventType
// create as many as the number of properties in MidiEventType and specialize GetProperty for each
struct Value;
struct Bytes;

template <class T, class Property>
struct GetProperty;

template <class T>
struct GetProperty<T, Value>
{
    static constexpr auto property = T::value;
};

template <class T>
struct GetProperty<T, Bytes>
{
    static constexpr auto property = T::bytes;
};

struct MidiEventTypes
{
    static constexpr MidiEventType<8,2> NOTE_OFF{};
    static constexpr MidiEventType<9,2> NOTE_ON{};
    static constexpr MidiEventType<10,2> KEY_AFTERTOUCH{};
    static constexpr MidiEventType<11,2> CONTROL_CHANGE{};
    static constexpr MidiEventType<12,1> PROGRAM_CHANGE{};
    static constexpr MidiEventType<13,1> CHANNEL_AFTERTOUCH{};
    static constexpr MidiEventType<14,2> PITCH_WHEEL_CHANGE{};
    static constexpr MidiEventType<-1,-1> INVALID{};

    // perform the lookup
    template <class Property>
    static constexpr auto get(int key)
    {
        return get_impl<Property, decltype(NOTE_OFF), decltype(NOTE_ON),
                decltype (KEY_AFTERTOUCH), decltype (CONTROL_CHANGE),
                decltype (PROGRAM_CHANGE), decltype (CHANNEL_AFTERTOUCH),
                decltype (PITCH_WHEEL_CHANGE)>::call(key);
    }

private:

    // class to automate the construction of if/else branches when looking up the key
    // our template parameters here will be MidiEventType<X,Y>
    template <class Property, class T, class... Rest>
    struct get_impl
    {
        static constexpr auto call(int key)
        {
            if(T::value == key) return GetProperty<T, Property>::property;
            else return get_impl<Property, Rest...>::call(key);
        }
    };

    // specialization for a single class
    // if the key is not found then return whatever we've set for the INVALID type
    template <class Property, class T>
    struct get_impl<Property, T>
    {
        static constexpr auto call(int key)
        {
            if(T::value == key) return GetProperty<T, Property>::property;
            else return GetProperty<decltype(INVALID), Property>::property;
        }
    };
};

int main()
{
    std::cout << MidiEventTypes::CHANNEL_AFTERTOUCH.bytes << std::endl;
    std::cout << MidiEventTypes::get<Value>(MidiEventTypes::NOTE_OFF) << std::endl;
    std::cout << MidiEventTypes::get<Bytes>(MidiEventTypes::CHANNEL_AFTERTOUCH) << std::endl;
    std::cout << MidiEventTypes::get<Bytes>(42) << std::endl; // invalid key, return INVALID.bytes
}
#include <iostream>
#include <array>

struct MidiEventType
{
    char value;
    char bytes;
    
    constexpr operator char() const { return value; }
};

struct MidiEventTypes
{
    static constexpr MidiEventType NOTE_OFF { 8, 2};
    static constexpr MidiEventType NOTE_ON { 9, 2};
    static constexpr MidiEventType KEY_AFTERTOUCH { 10, 2};
    static constexpr MidiEventType CONTROL_CHANGE { 11, 2};
    static constexpr MidiEventType PROGRAM_CHANGE  { 12, 1};
    static constexpr MidiEventType CHANNEL_AFTERTOUCH { 13, 1};
    static constexpr MidiEventType PITCH_WHEEL_CHANGE { 14, 2};
    
    static constexpr std::array<MidiEventType, 7> events{NOTE_OFF, NOTE_ON, KEY_AFTERTOUCH, CONTROL_CHANGE, PROGRAM_CHANGE, CHANNEL_AFTERTOUCH, PITCH_WHEEL_CHANGE};
    
    static constexpr auto get(char key)
    {
        // offset the key by 8 and then look into the array
        return events[(std::size_t)key - 8];
    }
};

int main()
{
    MidiEventTypes::get(MidiEventTypes::CONTROL_CHANGE).bytes;
    MidiEventTypes::get(MidiEventTypes::PROGRAM_CHANGE).bytes;
}
#include <iostream>
#include "const_string.h"
#include "const_map.h"

namespace midi
{
    using data_t = char;
    using string_t = const_string<32>; // 32 is big enough to hold strings in map

    namespace control
    {
        constexpr data_t NOTE_OFF = 8;
        constexpr data_t NOTE_ON = 9;
        constexpr data_t KEY_AFTERTOUCH = 10;
        constexpr data_t CONTROL_CHANGE = 11;
        constexpr data_t PROGRAM_CHANGE = 12;
        constexpr data_t CHANNEL_AFTERTOUCH = 13;
        constexpr data_t PITCH_WHEEL_CHANGE = 14;
    } /* namespace control */

    constexpr auto required_bytes = make_const_map<data_t, data_t>({
        {control::NOTE_OFF,2},
        {control::NOTE_ON,2},
        {control::KEY_AFTERTOUCH,2},
        {control::CONTROL_CHANGE,2},
        {control::PROGRAM_CHANGE,1},
        {control::CHANNEL_AFTERTOUCH,1},
        {control::PITCH_WHEEL_CHANGE,2}
    });

    constexpr auto str = make_const_map<data_t, string_t>({
        { control::NOTE_ON,"Note on" },
        { control::NOTE_OFF,"Note off" },
        { control::CONTROL_CHANGE, "Control change"},
        { control::CHANNEL_AFTERTOUCH, "Channel aftertouch"},
        { control::PITCH_WHEEL_CHANGE, "Pitch wheel change"}
    });

} /* namespace midi */

int main()
{
    static_assert(midi::control::NOTE_OFF == 8, "test failed");
    static_assert(midi::required_bytes[midi::control::NOTE_OFF] == 2, "test failed");
    static_assert(midi::required_bytes[13] == 1, "test failed");
    static_assert(midi::str[midi::control::NOTE_OFF] == "Note off", "test failed");

    return 0;
}
#include <iostream>
#include "const_string.h"
#include "const_map.h"

namespace midi_details
{
    using data_t = char;
    using string_t = const_string<32>;
}

constexpr midi_details::data_t MIDI_NOTE_OFF = 8;
constexpr midi_details::data_t MIDI_NOTE_ON = 9;
constexpr midi_details::data_t MIDI_KEY_AFTERTOUCH = 10;
constexpr midi_details::data_t MIDI_CONTROL_CHANGE = 11;
constexpr midi_details::data_t MIDI_PROGRAM_CHANGE = 12;
constexpr midi_details::data_t MIDI_CHANNEL_AFTERTOUCH = 13;
constexpr midi_details::data_t MIDI_PITCH_WHEEL_CHANGE = 14;

namespace midi_details
{
    constexpr auto required_bytes = make_const_map<data_t, data_t>({
        {MIDI_NOTE_OFF,2},
        {MIDI_NOTE_ON,2},
        {MIDI_KEY_AFTERTOUCH,2},
        {MIDI_CONTROL_CHANGE,2},
        {MIDI_PROGRAM_CHANGE,1},
        {MIDI_CHANNEL_AFTERTOUCH,1},
        {MIDI_PITCH_WHEEL_CHANGE,2}
        });

    constexpr auto str = make_const_map<data_t, string_t>({
            { MIDI_NOTE_ON,"Note on" },
            { MIDI_NOTE_OFF,"Note off" },
            { MIDI_CONTROL_CHANGE, "Control change"},
            { MIDI_CHANNEL_AFTERTOUCH, "Channel aftertouch"},
            { MIDI_PITCH_WHEEL_CHANGE, "Pitch wheel change"}
        });

    struct info_t
    {
        constexpr info_t(data_t r, string_t n) :
            required_bytes{ r },
            name{ n }
        {
        }

        data_t  required_bytes;
        string_t name;
    };

} /* namespace midi_details */

constexpr auto midi(midi_details::data_t value)
{
    return midi_details::info_t{ midi_details::required_bytes[value], midi_details::str[value] };
}

int main()
{
    static_assert(MIDI_NOTE_OFF == 8);
    static_assert(midi(MIDI_NOTE_OFF).required_bytes == 2, "test failed");
    static_assert(midi(MIDI_NOTE_OFF).name == "Note off", "test failed");

    return 0;
}
#include <iostream>
#include "const_string.h"
#include "const_map.h"

namespace midi
{
    using data_t = char;
    using string_t = const_string<32>; // 32 is big enough to hold strings in map

    namespace control
    {
        constexpr data_t NOTE_OFF = 8;
        constexpr data_t NOTE_ON = 9;
        constexpr data_t KEY_AFTERTOUCH = 10;
        constexpr data_t CONTROL_CHANGE = 11;
        constexpr data_t PROGRAM_CHANGE = 12;
        constexpr data_t CHANNEL_AFTERTOUCH = 13;
        constexpr data_t PITCH_WHEEL_CHANGE = 14;
    } /* namespace control */

    constexpr auto required_bytes = make_const_map<data_t, data_t>({
        {control::NOTE_OFF,2},
        {control::NOTE_ON,2},
        {control::KEY_AFTERTOUCH,2},
        {control::CONTROL_CHANGE,2},
        {control::PROGRAM_CHANGE,1},
        {control::CHANNEL_AFTERTOUCH,1},
        {control::PITCH_WHEEL_CHANGE,2}
    });

    constexpr auto str = make_const_map<data_t, string_t>({
        { control::NOTE_ON,"Note on" },
        { control::NOTE_OFF,"Note off" },
        { control::CONTROL_CHANGE, "Control change"},
        { control::CHANNEL_AFTERTOUCH, "Channel aftertouch"},
        { control::PITCH_WHEEL_CHANGE, "Pitch wheel change"}
    });

} /* namespace midi */

int main()
{
    static_assert(midi::control::NOTE_OFF == 8, "test failed");
    static_assert(midi::required_bytes[midi::control::NOTE_OFF] == 2, "test failed");
    static_assert(midi::required_bytes[13] == 1, "test failed");
    static_assert(midi::str[midi::control::NOTE_OFF] == "Note off", "test failed");

    return 0;
}
#include <iostream>
#include "const_string.h"
#include "const_map.h"

namespace midi_details
{
    using data_t = char;
    using string_t = const_string<32>;
}

constexpr midi_details::data_t MIDI_NOTE_OFF = 8;
constexpr midi_details::data_t MIDI_NOTE_ON = 9;
constexpr midi_details::data_t MIDI_KEY_AFTERTOUCH = 10;
constexpr midi_details::data_t MIDI_CONTROL_CHANGE = 11;
constexpr midi_details::data_t MIDI_PROGRAM_CHANGE = 12;
constexpr midi_details::data_t MIDI_CHANNEL_AFTERTOUCH = 13;
constexpr midi_details::data_t MIDI_PITCH_WHEEL_CHANGE = 14;

namespace midi_details
{
    constexpr auto required_bytes = make_const_map<data_t, data_t>({
        {MIDI_NOTE_OFF,2},
        {MIDI_NOTE_ON,2},
        {MIDI_KEY_AFTERTOUCH,2},
        {MIDI_CONTROL_CHANGE,2},
        {MIDI_PROGRAM_CHANGE,1},
        {MIDI_CHANNEL_AFTERTOUCH,1},
        {MIDI_PITCH_WHEEL_CHANGE,2}
        });

    constexpr auto str = make_const_map<data_t, string_t>({
            { MIDI_NOTE_ON,"Note on" },
            { MIDI_NOTE_OFF,"Note off" },
            { MIDI_CONTROL_CHANGE, "Control change"},
            { MIDI_CHANNEL_AFTERTOUCH, "Channel aftertouch"},
            { MIDI_PITCH_WHEEL_CHANGE, "Pitch wheel change"}
        });

    struct info_t
    {
        constexpr info_t(data_t r, string_t n) :
            required_bytes{ r },
            name{ n }
        {
        }

        data_t  required_bytes;
        string_t name;
    };

} /* namespace midi_details */

constexpr auto midi(midi_details::data_t value)
{
    return midi_details::info_t{ midi_details::required_bytes[value], midi_details::str[value] };
}

int main()
{
    static_assert(MIDI_NOTE_OFF == 8);
    static_assert(midi(MIDI_NOTE_OFF).required_bytes == 2, "test failed");
    static_assert(midi(MIDI_NOTE_OFF).name == "Note off", "test failed");

    return 0;
}
#include <iostream>
#include <map>
#include <vector>

enum class Events { NOTE_OFF, PROGRAM_CHANGE };

const std::map<Events, const int> bytes_per_events = {
    {Events::NOTE_OFF, 2},
    {Events::PROGRAM_CHANGE, 1}
    // ...
};

int main()
{
    std::cout << bytes_per_events.at(Events::NOTE_OFF) << " "
              << bytes_per_events.at(Events::PROGRAM_CHANGE) << "\n";
    return 0;
}

#include <iostream>

namespace MidiEvents {

struct MidiEventMetaData {
    int num_bytes;
    const char *str;
    uint32_t stuff;
};

enum MidiEventTypes {
   NOTE_OFF = 8,
   NOTE_ON = 9,
   KEY_AFTERTOUCH = 10,
   CONTROL_CHANGE = 11,
   PROGRAM_CHANGE = 12,
   CHANNEL_AFTERTOUCH = 13,
   PITCH_WHEEL_CHANGE = 14,
   OTHER = 17
};

constexpr MidiEventMetaData get(char event_type)
{
    switch (event_type) {
    default:
        break;
    case NOTE_OFF:
        return { 1, "note off", 7 }; 
    case NOTE_ON:
        return { 1, "note on", 20 }; 
    case KEY_AFTERTOUCH:
        return { 2, "aftertouch", 100 };
    }
    return { 0, "unknown", 0 };
}

constexpr char GetRequiredBytesByEventType(char event_type)
{
    return get(event_type).num_bytes;
}

constexpr const char *GetEventNameByType(char event_type)
{
    return get(event_type).str;
}

} // namespace MidiEvents

int main(int argc, char **argv)
{
    char num_bytes = MidiEvents::GetRequiredBytesByEventType(MidiEvents::KEY_AFTERTOUCH);
    const char * const name = MidiEvents::GetEventNameByType(MidiEvents::KEY_AFTERTOUCH);
    std::cout << "name = " << name << "\n"; 
    std::cout << "num_bytes = " << (int)num_bytes << "\n";
    return 0;
}

template <auto, auto, typename>
struct type_if_equal {};

template <auto k, typename T>
struct type_if_equal <k, k, T> : T {};

template <auto k, typename ... Ts>
struct map_t : type_if_equal<k, Ts::key, Ts>... {};
struct Midi {

    enum class Event : char {
        NOTE_OFF = 8,
        NOTE_ON,    // +1 till specified
        KEY_AFTERTOUCH,
        CONTROL_CHANGE,
        PROGRAM_CHANGE,
        CHANNEL_AFTERTOUCH,
        PITCH_WHEEL_CHANGE
    };
    
private:
    // D = Data (shortened for re-use in mapping)
    template <Event e, int bytes /* other data */ >
    struct D {
        constexpr static Event key = e;
        constexpr static int BytesRequired = bytes;
        /* store other data here */
    };
    
public:
    
    template <Event e>
    using Info = map_t<e,
        D<Event::NOTE_OFF, 2>,
        D<Event::NOTE_ON, 2>,
        D<Event::KEY_AFTERTOUCH, 2>,
        D<Event::CONTROL_CHANGE, 2>,
        D<Event::PROGRAM_CHANGE, 1>,
        D<Event::CHANNEL_AFTERTOUCH, 1>,
        D<Event::PITCH_WHEEL_CHANGE, 2>>;
};
template <int b /* other data */ >
struct Data {
    constexpr static int BytesRequired = b;
    /* store other data here */
};

template <Event>
struct Info {};

// Specify mappings:
template <>
struct Info <Event::NOTE_OFF> : Data<2> {};

template <>
struct Info <Event::NOTE_ON> : Data<2> {};

template <>
struct Info <Event::KEY_AFTERTOUCH> : Data<2> {};

// ...
template <auto, auto, typename>
struct type_if_equal {};

template <auto k, typename T>
struct type_if_equal <k, k, T> : T {};

template <auto k, typename ... Ts>
struct map_t : type_if_equal<k, Ts::key, Ts>... {};
struct Midi {

    enum class Event : char {
        NOTE_OFF = 8,
        NOTE_ON,    // +1 till specified
        KEY_AFTERTOUCH,
        CONTROL_CHANGE,
        PROGRAM_CHANGE,
        CHANNEL_AFTERTOUCH,
        PITCH_WHEEL_CHANGE
    };
    
private:
    // D = Data (shortened for re-use in mapping)
    template <Event e, int bytes /* other data */ >
    struct D {
        constexpr static Event key = e;
        constexpr static int BytesRequired = bytes;
        /* store other data here */
    };
    
public:
    
    template <Event e>
    using Info = map_t<e,
        D<Event::NOTE_OFF, 2>,
        D<Event::NOTE_ON, 2>,
        D<Event::KEY_AFTERTOUCH, 2>,
        D<Event::CONTROL_CHANGE, 2>,
        D<Event::PROGRAM_CHANGE, 1>,
        D<Event::CHANNEL_AFTERTOUCH, 1>,
        D<Event::PITCH_WHEEL_CHANGE, 2>>;
};
template <int b /* other data */ >
struct Data {
    constexpr static int BytesRequired = b;
    /* store other data here */
};

template <Event>
struct Info {};

// Specify mappings:
template <>
struct Info <Event::NOTE_OFF> : Data<2> {};

template <>
struct Info <Event::NOTE_ON> : Data<2> {};

template <>
struct Info <Event::KEY_AFTERTOUCH> : Data<2> {};

// ...
template <auto, auto, typename>
struct type_if_equal {};

template <auto k, typename T>
struct type_if_equal <k, k, T> : T {};

template <auto k, typename ... Ts>
struct map_t : type_if_equal<k, Ts::key, Ts>... {};
struct Midi {

    enum class Event : char {
        NOTE_OFF = 8,
        NOTE_ON,    // +1 till specified
        KEY_AFTERTOUCH,
        CONTROL_CHANGE,
        PROGRAM_CHANGE,
        CHANNEL_AFTERTOUCH,
        PITCH_WHEEL_CHANGE
    };
    
private:
    // D = Data (shortened for re-use in mapping)
    template <Event e, int bytes /* other data */ >
    struct D {
        constexpr static Event key = e;
        constexpr static int BytesRequired = bytes;
        /* store other data here */
    };
    
public:
    
    template <Event e>
    using Info = map_t<e,
        D<Event::NOTE_OFF, 2>,
        D<Event::NOTE_ON, 2>,
        D<Event::KEY_AFTERTOUCH, 2>,
        D<Event::CONTROL_CHANGE, 2>,
        D<Event::PROGRAM_CHANGE, 1>,
        D<Event::CHANNEL_AFTERTOUCH, 1>,
        D<Event::PITCH_WHEEL_CHANGE, 2>>;
};
template <int b /* other data */ >
struct Data {
    constexpr static int BytesRequired = b;
    /* store other data here */
};

template <Event>
struct Info {};

// Specify mappings:
template <>
struct Info <Event::NOTE_OFF> : Data<2> {};

template <>
struct Info <Event::NOTE_ON> : Data<2> {};

template <>
struct Info <Event::KEY_AFTERTOUCH> : Data<2> {};

// ...

Is there a way to avoid implicit conversion to void*?

copy iconCopydownload iconDownload
#include <iostream>
#include <string>
#include <type_traits>

void api(void* p) { // your original API
    std::cout << "void* " << p << '\n';
}

template<class T>
void api_wrapper(T* p) { // your wrapper
    // let constness fail in the original api instead of in the static_assert:
    using type = std::remove_const_t<T>*;

    static_assert(
        // add your approved types here
        std::is_convertible_v<type, std::ostream*> ||
        std::is_convertible_v<type, std::string*>,
        "Not an approved type"
    );
    api(p);
}

int main() {
    std::string foo;
    api_wrapper(&std::cout);
    api_wrapper(&foo);
    //api_wrapper(&std::cin); // compile time error "Not an approved type"
}
    static_assert(
        // add your disapproved types here
        not std::is_convertible_v<type, std::ostream*> &&
        not std::is_convertible_v<type, std::string*>,
        "Not an approved type"
    );
#include <iostream>
#include <string>
#include <type_traits>

void api(void* p) { // your original API
    std::cout << "void* " << p << '\n';
}

template<class T>
void api_wrapper(T* p) { // your wrapper
    // let constness fail in the original api instead of in the static_assert:
    using type = std::remove_const_t<T>*;

    static_assert(
        // add your approved types here
        std::is_convertible_v<type, std::ostream*> ||
        std::is_convertible_v<type, std::string*>,
        "Not an approved type"
    );
    api(p);
}

int main() {
    std::string foo;
    api_wrapper(&std::cout);
    api_wrapper(&foo);
    //api_wrapper(&std::cin); // compile time error "Not an approved type"
}
    static_assert(
        // add your disapproved types here
        not std::is_convertible_v<type, std::ostream*> &&
        not std::is_convertible_v<type, std::string*>,
        "Not an approved type"
    );
// API function
void api(void* p) {
    // ... 
}

// Special case for nullptr
inline void api(std::nullptr_t) {
    api((void*)nullptr);
}

// Everything else is disabled
template <class ...T>
void api(T&&... t) = delete;

int main() {
    int i = 0;
    void* p = &i;
    api(p); // Compiles
    // api(&i); // Doesn't compile
}
#include <cstdint>

using api_handle = std::uintptr_t;

inline api_handle make_api_handle(const char* p)
{
  return (api_handle)(const void*)p;
}

inline api_handle make_api_handle(const int* p)
{
  return (api_handle)(const void*)p;
}

Community Discussions

Trending Discussions on runtime
  • Why do Switch and ListView controls in MAUI not update with 2-way binding?
  • Java, Intellij IDEA problem Unrecognized option: --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED
  • Android app won't build -- The minCompileSdk (31) specified in a dependency's androidx.work:work-runtime:2.7.0-beta01
  • Flutter iOS Error Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libamsupport.dylib (0x203913130)
  • How to open emulators in different windows at Android Studio (Bumblebee | 2021.1.1)?
  • Could not resolve com.google.guava:guava:30.1-jre - Gradle project sync failed. Basic functionality will not work properly - in kotlin project
  • .NET 6.0 not showing in Visual Studio 2022 (General Release)
  • What is 'serviceability memory category' of Native Memory Tracking?
  • Error about Android Studio on Macbook M1: An error occurred while trying to compute required packages
  • Google app engine deployment fails- Error while finding module specification for 'pip' (AttributeError: module '__main__' has no attribute '__file__')
Trending Discussions on runtime

QUESTION

Why do Switch and ListView controls in MAUI not update with 2-way binding?

Asked 2022-Apr-11 at 09:33

This question is about two MAUI controls (Switch and ListView) - I'm asking about them both in the same question as I'm expecting the root cause of the problem to be the same for both controls. It's entirely possible that they're different problems that just share some common symptoms though. (CollectionView has similar issues, but other confounding factors that make it trickier to demonstrate.)

I'm using 2-way data binding in my MAUI app: changes to the data can either come directly from the user, or from a background polling task that checks whether the canonical data has been changed elsewhere. The problem I'm facing is that changes to the view model are not visually propagated to the Switch.IsToggled and ListView.SelectedItem properties, even though the controls do raise events showing that they've "noticed" the property changes. Other controls (e.g. Label and Checkbox) are visually updated, indicating that the view model notification is working fine and the UI itself is generally healthy.

Build environment: Visual Studio 2022 17.2.0 preview 2.1
App environment: Android, either emulator "Pixel 5 - API 30" or a real Pixel 6

The sample code is all below, but the fundamental question is whether this a bug somewhere in my code (do I need to "tell" the controls to update themselves for some reason?) or possibly a bug in MAUI (in which case I should presumably report it)?

Sample code

The sample code below can be added directly a "File new project" MAUI app (with a name of "MauiPlayground" to use the same namespaces), or it's all available from my demo code repo. Each example is independent of the other - you can try just one. (Then update App.cs to set MainPage to the right example.)

Both examples have a very simple situation: a control with two-way binding to a view-model, and a button that updates the view-model property (to simulate "the data has been modified elsewhere" in the real app). In both cases, the control remains unchanged visually.

Note that I've specified {Binding ..., Mode=TwoWay} in both cases, even though that's the default for those properties, just to be super-clear that that isn't the problem.

The ViewModelBase code is shared by both examples, and is simply a convenient way of raising INotifyPropertyChanged.PropertyChanged without any extra dependencies:

ViewModelBase.cs:

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace MauiPlayground;

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public bool SetProperty<T>(ref T field, T value, [CallerMemberName] string name = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value))
        {
            return false;
        }
        field = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        return true;
    }
}
Switch sample code

SwitchDemo.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiPlayground.SwitchDemo">
    <StackLayout>
        <Label Text="Switch binding demo" />
        <HorizontalStackLayout>
            <Switch x:Name="switchControl"
                    IsToggled="{Binding Toggled, Mode=TwoWay}"
                    Toggled="Toggled" />
            <CheckBox IsChecked="{Binding Toggled, Mode=TwoWay}" />
            <Label Text="{Binding Toggled}" />
        </HorizontalStackLayout>

        <Button Text="Toggle" Clicked="Toggle" />
        <Label x:Name="manualLabel1" Text="Value set in button click handler" />
        <Label x:Name="manualLabel2" Text="Value set in toggled handler" />
    </StackLayout>
</ContentPage>

SwitchDemo.cs

namespace MauiPlayground;

public partial class SwitchDemo : ContentPage
{
    public SwitchDemo()
    {
        InitializeComponent();
        BindingContext = new ViewModel();
    }

    private void Toggle(object sender, EventArgs e)
    {
        var vm = (ViewModel)BindingContext;
        vm.Toggled = !vm.Toggled;
        manualLabel1.Text = $"Set in click handler: {switchControl.IsToggled}";
    }

    private void Toggled(object sender, ToggledEventArgs e) =>
        manualLabel2.Text = $"Set in toggled handler: {switchControl.IsToggled}";

    private class ViewModel : ViewModelBase
    {
        private bool toggled;
        public bool Toggled
        {
            get => toggled;
            set => SetProperty(ref toggled, value);
        }
    }
}

Screenshot of the emulator after clicking on the "Toggle" button, which updates the view-model:

Demonstration of Switch issue

Notes:

  • The checkbox (bound to the same VM property) has updated
  • The label next to the checkbox (bound to the same VM property) has updated
  • The label below the button indicates that switch.IsToggled is true
  • The label below that indicates that the Switch.Toggled event has been raised
  • The Switch itself has not changed visible state

Clicking on the Switch control directly does visually toggle it.

ListView sample code

ListViewDemo.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiPlayground.ListViewDemo">
    <StackLayout>
        <Label Text="ListView binding demo" />
        <ListView x:Name="listView" ItemsSource="{Binding Items}"
                  SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
                  VerticalOptions="Start"
                  ItemSelected="ItemSelected"/>
        <Label Text="{Binding SelectedItem}" />
        <Button Text="Toggle" Clicked="Toggle" />
        <Label x:Name="manualLabel1" Text="Text set in button click handler" />
        <Label x:Name="manualLabel2" Text="Text set in item selected handler" />
    </StackLayout>
</ContentPage>

ListViewDemo.cs

namespace MauiPlayground;

public partial class ListViewDemo : ContentPage
{
    public ListViewDemo()
    {
        InitializeComponent();
        BindingContext = new ViewModel();
    }

    private void Toggle(object sender, EventArgs e)
    {
        var vm = (ViewModel)BindingContext;
        vm.SelectedItem = vm.SelectedItem == "First" ? "Second" : "First";
        manualLabel1.Text = $"Set in click handler: {listView.SelectedItem}";
    }

    private void ItemSelected(object sender, EventArgs e) =>
        manualLabel2.Text = $"Set in item selected handler: {listView.SelectedItem}";

    private class ViewModel : ViewModelBase
    {
        public List<string> Items { get; } = new List<string> { "First", "Second" };

        private string selectedItem = "First";
        public string SelectedItem
        {
            get => selectedItem;
            set => SetProperty(ref selectedItem, value);
        }
    }
}

Screenshot of the emulator after clicking on the "Toggle" button, which updates the view-model:

Demonstration of ListView issue

Notes:

  • The label below the list view (bound to the same VM property) has updated
  • The label below the button indicates that listView.SelectedItem has the new value
  • The label below that indicates that the ListView.ItemSelected event has been raised
  • The ListView itself appears to have no selected item

Interestingly, the list view does actually change appearance: before clicking on the button, the first item is visually selected (in orange). Selecting an item from the list manually updates all the properties, but we don't see the selected item in orange.

ANSWER

Answered 2022-Apr-09 at 18:07

These both may be bugs with the currently released version of MAUI.

This bug was recently posted and there is already a fix for the Switch to address this issue.

Source https://stackoverflow.com/questions/71810199

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install runtime

You can download it from GitHub.

Support

We welcome contributions! Many people all over the world have helped make this project better.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

Share this Page

share link
Reuse Pre-built Kits with runtime
Consider Popular C# Libraries
Try Top Libraries by dotnet
Compare C# Libraries with Highest Support
Compare C# Libraries with Highest Quality
Compare C# Libraries with Highest Security
Compare C# Libraries with Permissive License
Compare C# Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.